第1年4月23日 swift Moya
1.Moya
TargetType => EndpointCloseure => endPoint => RequestClosure => Request
https://segmentfault.com/a/1190000012997081
static let provider = MoyaProvider<API>(endpointClosure: myEndpointClosure)
provider.request(target) { (result) in switch result{ case let .success(response): if let json = try? response.mapJSON() as! [String:Any]{ successCallback(json) } else{ print("服务器连接成功,数据获取失败") } case let .failure(error): failureCallback(error.errorDescription!) } }
extension API:TargetType{ var baseURL: URL { return URL(string: "https://www.baidu.com?search=")! } var path: String { switch self { case .login: return "Login" case .getAllProjUser: return "GetAllProj" } } var getPartmeters: [String: Any]{ switch self { case let .login(dict): return dict case .getAllProjUser: return [:] } } var task: Task { return .requestParameters(parameters: getPartmeters, encoding: JSONEncoding.default) } var method: Moya.Method { return .post } var sampleData: Data { return Data() } var headers: [String : String]? { return nil } }
import Moya /// 超时时长 private var requestTimeOut:Double = 30 ///endpointClosure private let myEndpointClosure = { (target: API) -> Endpoint in ///主要是为了解决URL带有?无法请求正确的链接地址的bug let url = target.baseURL.absoluteString + target.path var endpoint = Endpoint( url: url, sampleResponseClosure: { .networkResponse(200, target.sampleData) }, method: target.method, task: target.task, httpHeaderFields: target.headers ) switch target { case .login: requestTimeOut = 5//按照项目需求针对单个API设置不同的超时时长 return endpoint default: requestTimeOut = 30//设置默认的超时时长 return endpoint } } struct Network { static let provider = MoyaProvider<API>(endpointClosure: myEndpointClosure) static func request(_ target: API, successCallback: @escaping ([String:Any]) -> Void, failure failureCallback: @escaping (String) -> Void){ provider.request(target) { (result) in switch result{ case let .success(response): if let json = try? response.mapJSON() as! [String:Any]{ successCallback(json) } else{ print("服务器连接成功,数据获取失败") } case let .failure(error): failureCallback(error.errorDescription!) } } } // MARK: - 取消所有网络请求 static func cancelAllRequest(){ provider.manager.session.getAllTasks { (tasks) in tasks.forEach{ print("取消网络请求一次") $0.cancel() } } } }
https://www.jianshu.com/p/25c61c81b56b
2.moya+rxswift
MoyaProvider+Rx.swift
extension MoyaProvider: ReactiveCompatible {} public extension Reactive where Base: MoyaProviderType { /// Designated request-making method. /// /// - Parameters: /// - token: Entity, which provides specifications necessary for a `MoyaProvider`. /// - callbackQueue: Callback queue. If nil - queue from provider initializer will be used. /// - Returns: Single response object. func request(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Single<Response> { return Single.create { [weak base] single in let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in switch result { case let .success(response): single(.success(response)) case let .failure(error): single(.error(error)) } } return Disposables.create { cancellableToken?.cancel() } } }
2)
https://www.jianshu.com/p/87a263fc28e8
3.RxNetwork
public extension TargetType { func request() -> Single<Moya.Response> { return Network.default.provider.rx.request(.target(self)) } }
public extension MoyaProvider { convenience init(configuration: Network.Configuration) { let endpointClosure = { target -> Endpoint in MoyaProvider.defaultEndpointMapping(for: target) .adding(newHTTPHeaderFields: configuration.addingHeaders(target)) .replacing(task: configuration.replacingTask(target)) } let requestClosure = { (endpoint: Endpoint, closure: RequestResultClosure) -> Void in do { var request = try endpoint.urlRequest() request.timeoutInterval = configuration.timeoutInterval print "===" + request closure(.success(request)) } catch MoyaError.requestMapping(let url) { closure(.failure(.requestMapping(url))) } catch MoyaError.parameterEncoding(let error) { closure(.failure(.parameterEncoding(error))) } catch { closure(.failure(.underlying(error, nil))) } } self.init(endpointClosure: endpointClosure, requestClosure: requestClosure, manager: configuration.manager, plugins: configuration.plugins) } }