Swift网络请求框架Moya的使用

GitHub地址:https://github.com/Moya/Moya.git
Moya基于Alamofire进行封装,使用更加简单,维护更加方便。
1.使用CocoaPods导入Moya:

pod 'Moya', '~> 11.0.2'

2.创建一个对象实现TargetType协议的方法

import Foundation
import Moya

enum ScanServer {
    case qrLogin(appname: String, nonce: String, address: String)
    case qrLoginConfirm(appname: String, nonce: String, address: String, confirm: String)
}

extension ScanServer: TargetType {
    
    var headers: [String : String]? {
        return ["Content-type" : "application/json"]
    }
    
    var baseURL: URL {
        return URL(string: GlobalConfig.current.scanServerBase)!
    }
    
    var path: String {
        switch self {
        case .qrLogin(_):
            return "/qrlogin"
        case .qrLoginConfirm(_):
            return "/qrconfirm"
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .qrLogin(_):
            return .get
        default:
            return .post
        }
    }
    
    var parameters: [String: Any]? {
        var paramsDict: [String : Any] = [:]
        switch self {
        case .qrLogin(let appname, let nonce, let address):
            paramsDict["appname"] = appname
            paramsDict["nonce"] = nonce
            paramsDict["address"] = address
        case .qrLoginConfirm(let appname, let nonce, let address, let confirm):
            paramsDict["appname"] = appname
            paramsDict["nonce"] = nonce
            paramsDict["address"] = address
            paramsDict["confirm"] = confirm
        }
        return paramsDict
    }
    
    var parameterEncoding: ParameterEncoding {
        return URLEncoding.default
    }
    
    var sampleData: Data {
        return "".data(using: .utf8)!
    }
    
    var task: Task {
        switch self {
        case .qrLogin(_):
            return .requestParameters(parameters: parameters ?? [:], encoding: URLEncoding.default)//get方式参数拼接成url
        default:
            return .requestParameters(parameters: parameters ?? [:], encoding: JSONEncoding.default)//post方式参数是json格式
        }
    }
    
}

3.创建一个对象实现MoyaProviderType协议的方法

import Moya
import Result
import SwiftyJSON

enum ProviderError: LocalizedError {
    case server
    case data
    case message(msg: String)
    
    var description: String {
        switch self {
        case .server:
            return "Failed to connect to server".localized
        case .data:
            return "Failed to get data".localized
        case .message(let msg):
            return msg
        }
    }
}

let networkPlugin = NetworkActivityPlugin { (change, _) in
    switch(change){
    case .ended:
        DispatchQueue.main.async {
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
        }
    case .began:
        DispatchQueue.main.async {
            UIApplication.shared.isNetworkActivityIndicatorVisible = true
        }
    }
}

let scanClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider.RequestResultClosure) in
    do {
        var request: URLRequest = try endpoint.urlRequest()
        request.timeoutInterval = 30
        done(.success(request))
    } catch  {
        print("\(error)")
    }
}

class ScanProvider {
    
    static let shared = ScanProvider()
    
    let provider = MoyaProvider(requestClosure: scanClosure, plugins: [networkPlugin])
    
    private func failureAction(error: ProviderError) {
        if NetworkingManager.status == .none || NetworkingManager.status == .unknown {
            Toast.showMessage(message: NetworkingManager.status.description)
        } else {
            Toast.showMessage(message: error.description)
        }
    }
    
    func qrLogin(appname: String,
                 nonce: String,
                 address: String,
                 completion: @escaping (Result) -> Void) {
        provider.request(.qrLogin(
            appname: appname,
            nonce: nonce,
            address: address)) { result in
                switch result {
                case .success(let responseData):
                    if let response = JSONResponseFormatter(responseData.data) {
                        print(response)
                        if let status = response["state"] as? Int {
                            completion(.success(status == 1 ? true : false))
                        }
                    }
                case .failure(_):
                    self.failureAction(error: .server)
                    completion(.failure(.server))
                }
        }
    }
    
    func qrLoginConfirm(appname: String,
                        nonce: String,
                        address: String,
                        confirm: String,
                        completion: @escaping (Result) -> Void) {
        provider.request(.qrLoginConfirm(
            appname: appname,
            nonce: nonce,
            address: address,
            confirm: confirm)) { result in
                switch result {
                case .success(let responseData):
                    if let response = JSONResponseFormatter(responseData.data) {
                        print(response)
                        if let status = response["state"] as? Int {
                            completion(.success(status == 1 ? true : false))
                        }
                    }
                case .failure(_):
                    self.failureAction(error: .server)
                    completion(.failure(.server))
                }
        }
    }
}

4.发起请求

ScanProvider.shared.qrLogin(
    appname: result.qrStringAppName,
    nonce: result.qrStringNonce,
    address: result.address
) {[weak self] (res) in
    guard let `self` = self else { return }
    switch res {
    case .success(_):
        print("success")
    case .failure(_):
        print("failure")
    }
}

你可能感兴趣的:(Swift)