Moya 网络请求封装

2020-11-10  本文已影响0人  小王在努力

1、前言

任何网络请求主要由三部分构成
a、域名 : 我们经常说的URL
b、头参数 : 我们说的header
c、body : 网络请求参数存放的地方

2、定义一个枚举

每一个请求方法一个枚举上代码
public enum ApiMoya{
    //about user
    case login(username :String,password :String)
    //data upload
    case uploadVideo(data :Data)
}

3、创建一个文件

该文件继承 TargetType并且实现 TargetType的协议

extension ApiMoya : TargetType{
    public var baseURL: URL {
        switch self {
        case .uploadVideo:
            return URL(string: BaseMacro.apiUploadHost())!
        default:
            return URL(string: BaseMacro.apiHost())!
        }
    }
    public var task: Task {
        var params : [String : String] = [:]
        switch self {
        case let .login(username: username, password: password):
            params = ["username":username,"password":password]
            break
        case let .uploadVideo(data: data):
            let time = String().timeStamp
            let auto_key = "FoFHDov5mTn3OriLeE9u3loOnIL6tp7q" + time
            params = ["from":"6","uuid":BaseMacro.uuid()," time":time,"auth_key":auto_key.md5String]
            let formData: [Moya.MultipartFormData] = [Moya.MultipartFormData(provider: .data(data), name: "video", fileName: "video.mp4", mimeType: "video/mp4")]
            return .uploadCompositeMultipart(formData, urlParameters: params)
        default:
            break;
        }
        let code = ApiEncry.encodeData(params:params)
        return .requestParameters(parameters: code, encoding: URLEncoding.default)
    }
    public var path: String {
        switch self {
        case .login:
            return "cps/user/login"
        case .uploadVideo:
            return "video"
        }
    }
    public var method: Moya.Method {
        return .post
    }
    public var headers: [String : String]? {
        switch self {
        case .uploadVideo:
            return [:]//["Content-type" : "multipart/form-data"]
        default:
            return [:]
        }
    }
    public var sampleData: Data {
        return Data(base64Encoded: "just for test")!
    }

注意

a、baseURL :网络请求存放的域名
b、task :网络请求的boday
c、headers :网络请求的头参数
d、method :网络请求的方式 POST、GET、PUT、DELETE
e、path :一般是域名后名携带的参数比如域名是http://www.baidu.com 经常需要在域名后添加比如login ,http://www.baidu.com/login,这里path就是login,也可以为空
f、sampleData :单元测试使用

4、基于ApiMoya的封装

extension ApiMoya{
    public static func request(target : ApiMoya,sucesss:@escaping ((_ object : JSON) ->()),failure:@escaping ((_ error : String) ->())){
        let moya = MoyaProvider<ApiMoya>()
        moya.request(target, callbackQueue: DispatchQueue.main, progress: nil) { (result) in
            switch result{
            case let .success(respond):do{
                let json = JSON(respond.data)
                sucesss(json)
            }
            case let .failure(error):do {
                failure(error.errorDescription!)
                break
            }
            }
        }
    }
}

5、方法的调用

ApiMoya.request(target: .login(username: self.accountView.text!, password: self.pwdView.text!)) { (json) in
                print(json)
 } failure: { (error) in

  }

6、网络请求超时设置

private let timeOut = { (endpoint: Endpoint, done: @escaping MoyaProvider<ApiMoya>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 10
        done(.success(request))
    } catch {
        return
    }
}

只需要在4这一步调用就可以了,比如

let moya = MoyaProvider<ApiMoya>(requestClosure:timeOut)
上一篇下一篇

猜你喜欢

热点阅读