wsift

关于Moya的MultiTarget和证书自签名

2017-08-21  本文已影响208人  meowboss

简介:

运用MultiTarget相比TargetType可以实现业务分离和将不同的HTTPMethod隔开。

实现:

创建ZYApi.swift文件,代码如下:

extension ZY where Base: MoyaProvider<MultiTarget> {
    @discardableResult
    open func request(_ target: TargetType, completion: @escaping Moya.Completion) -> Cancellable {
        return base.request(MultiTarget(target), queue: nil, completion: completion)
    }
    @discardableResult
//Post是实现TargetType协议的枚举
    func post(_ target: Post, completion: @escaping Moya.Completion) -> Cancellable {
        return base.request(MultiTarget(target), queue: nil, completion: completion)
    }
    @discardableResult
//Get是实现TargetType协议的枚举
    func get(_ target: Get, completion: @escaping Moya.Completion) -> Cancellable {
        return base.request(MultiTarget(target), queue: nil, completion: completion)
    }

}
//TODO:waiting for swift 4 https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#conditional-conformances-
extension MoyaProvider: ZYCompatible /*where Target: MultiTarget*/{}

let publicParamEndpointClosure = { (target: MultiTarget) -> Endpoint<MultiTarget> in
    let url = target.path.isEmpty ? target.baseURL.absoluteString : target.baseURL.appendingPathComponent(target.path).absoluteString
    let endpoint = Endpoint<MultiTarget>(url: url, sampleResponseClosure: { .networkResponse(200, target.sampleData) }, method: target.method, parameters: target.parameters, parameterEncoding: target.parameterEncoding)
    return endpoint.adding(newHTTPHeaderFields: ["Content-Type" : "application/json"])
}

let zyApi:ZY<MoyaProvider<MultiTarget>> = { () -> MoyaProvider<MultiTarget> in
    let manager = Manager(configuration: URLSessionConfiguration.default,serverTrustPolicyManager:CustomServerTrustPoliceManager())
    let provider = MoyaProvider(endpointClosure: publicParamEndpointClosure, manager:manager,plugins:[NetworkLoggerPlugin(verbose: true)])
    return provider
}().zy

class CustomServerTrustPoliceManager : ServerTrustPolicyManager {
    override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
        return .disableEvaluation
    }
    public init() {
        super.init(policies: [:])
    }
}

通过命名空间,我们调用MultiTarget的方式和TargetType的方式没什么不同了,我们可以写很多个业务类型的TargetType,并且像使用正常TargetType的方式使用MultiTarget,同时我们又新创建了post方法和get方法,这样HTTPMethod就一目了然了。
这里有用到命名空间的知识,详情可以见我的这篇文章。证书自签名参考了一个国外友人的设计,链接在这里

下一篇:代码片段

参考资料:

SelfSignedMoya

上一篇下一篇

猜你喜欢

热点阅读