美文网首页
Swift4 Moya 解释说明

Swift4 Moya 解释说明

作者: 巴糖 | 来源:发表于2018-01-04 11:46 被阅读199次
    import Foundation
    import Moya
    
    enum BJNetworkTool {
        case zen
        case showUser(id: Int)
        case createUser(firstName: String, lastName: String)
        case updateUser(id: Int, firstName: String, lastName: String)
        case showAccounts
        case uploadData(firstName: String, file: Data)
    }
    
    extension BJNetworkTool: TargetType {
        
        /// The target's base `URL`.
        /// baseURL 统一基本的URL
        var baseURL: URL {
            return URL(string: "https://api.myservice.com")!
        }
        
        /// The path to be appended to `baseURL` to form the full `URL`.
        /// path字段会追加至baseURL后面
        var path: String {
            switch self {
            case .zen:
                return "/zen"
            case .showUser(let id), .updateUser(let id, _, _):
                return "/users/\(id)"
            case .createUser(_, _):
                return "/users"
            case .showAccounts:
                return "/accounts"
            case .uploadData:
                return "/upload"
            }
        }
        
        /// The HTTP method used in the request.
        /// HTTP的请求方式
        var method: Moya.Method {
            switch self {
            case .zen, .showUser, .showAccounts:
                return .get
            case .createUser, .updateUser:
                return .post
            case .uploadData:
                return .post
            }
        }
        
        /// The type of HTTP task to be performed.
        /// 将要被执行的任务(请求:request 下载:upload 上传:download)
        var task: Task {
            switch self {
            case .zen, .showUser, .showAccounts:
                // Send no parameters
                return .requestPlain
            case let .updateUser(_, firstName, lastName):
                // Always sends parameters in URL, regardless of which HTTP method is used
                return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: URLEncoding.queryString)
            case let .createUser(firstName, lastName):
                // Always send parameters as JSON in request body
                return .requestParameters(parameters: ["first_name": firstName, "last_name": lastName], encoding: JSONEncoding.default)
            case let .uploadData(firstName: String, file: Data)
                let m1 = MultipartFormData(provider: MultipartFormData.FormDataProvider.data(dataImage!), name: "file" ,fileName: "file.png" , mimeType: "image/png")
                let strData1 = firstName.data(using: .utf8)
                let m2 = MultipartFormData(provider: MultipartFormData.FormDataProvider.data(strData1!), name: BJRequestKeyModel)
                return .uploadMultipart([m1, m2])
            }
        }
        
        /// Provides stub data for use in testing.
        /// 这里用于单元测试,不需要的就像我一样随便写写
        var sampleData: Data {
            switch self {
            case .zen:
                return "Half measures are as bad as nothing at all.".utf8Encoded
            case .showUser(let id):
                return "{\"id\": \(id), \"first_name\": \"Harry\", \"last_name\": \"Potter\"}".utf8Encoded
            case .createUser(let firstName, let lastName):
                return "{\"id\": 100, \"first_name\": \"\(firstName)\", \"last_name\": \"\(lastName)\"}".utf8Encoded
            case .updateUser(let id, let firstName, let lastName):
                return "{\"id\": \(id), \"first_name\": \"\(firstName)\", \"last_name\": \"\(lastName)\"}".utf8Encoded
            case .showAccounts:
                // Provided you have a file named accounts.json in your bundle.
                guard let url = Bundle.main.url(forResource: "accounts", withExtension: "json"),
                    let data = try? Data(contentsOf: url) else {
                        return Data()
                }
                return data
            }
        }
        
        var headers: [String: String]? {
            return ["Content-type": "application/json"]
        }
        
    }
    
    // MARK: - Helpers
    private extension String {
        var urlEscaped: String {
            return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
        }
        
        var utf8Encoded: Data {
            return data(using: .utf8)!
        }
    }
    
    
            let provider = MoyaProvider<BJNetworkTool>().request(.recommend(page: 1, pagesize: 8) { result in
            switch result {
            case let .success(moyaResponse):
                do {
                    let data = try moyaResponse.mapJSON()
                    print("data\(data)")
                }
                catch {
                    // show an error to your user
                }
                let statusCode = moyaResponse.statusCode
    
                print("statusCode\(statusCode)")
            // do something with the response data or statusCode
            case let .failure(error): break
                // this means there was a network failure - either the request
                // wasn't sent (connectivity), or no response was received (server
                // timed out).  If the server responds with a 4xx or 5xx error, that
                // will be sent as a ".success"-ful response.
            }
    

    相关文章

      网友评论

          本文标题:Swift4 Moya 解释说明

          本文链接:https://www.haomeiwen.com/subject/iqcrnxtx.html