Moya簡介
一句話來講,Moya是對Alamofire的封裝,讓開發人員更加優雅的使用Alamofire。
基本用法
-
定義介面列舉
public enum HFAPI { case login(String, String, String) //登入介面 case smscode(String) //登入,傳送驗證碼 } 複製程式碼
-
擴充列舉並實現TargetType,程式碼詳解如下:
extension HFAPI: TargetType { public var baseURL: URL { return URL.init(string: "介面域名")!; } public var path: String { switch self { case .login: return "login介面路徑" case .smscode: return "smscode介面路徑" } } //請求介面時使用的方法 public var method: Moya.Method { switch self { case .login: return .post case .smscode: return .get } } //請求介面時對應的請求引數 public var task: Task { var params:[String : Any] = [:] params["v"] = ProjectInfo.appVersionWithOutPoint() params["dev"] = ProjectInfo.platform() switch self { case.login(let smsCodeToken, let smsCode, let phone): params["smsCodeToken"] = smsCodeToken params["smsCode"] = smsCode params["phone"] = phone break; case .smscode(let phone): params["phone"] = phone break; } return .requestParameters(parameters: params, encoding: URLEncoding.default) } //header資訊 public var headers: [String : String]? { var header: [String:String] = [:] let token = HFDefault.getToken() if token.count > 0 { header["X-Token"] = token } return header } //用於單元測試 public var sampleData: Data { switch self { case .login: return "{\"id\": \"1\", \"first_name\": \"Harry\", \"last_name\": \"Potter\"}".data(using: String.Encoding.utf8)! default: return Data() } } } 複製程式碼
sampleData
是用於單元測試的,我們可以使用Xcode自帶的單元測試工具來自測,測試用例如下:func testSmscodeAPI() { let loginProvitder = MoyaProvider<HFAPI>(stubClosure: MoyaProvider.immediatelyStub) loginProvitder.request(.smscode("17755558888")) { result in switch result { case let .success(moyaResponse): let statusCode = moyaResponse.statusCode // Int - 200, 401, 500, etc let data = String.init(data: moyaResponse.data, encoding: String.Encoding.utf8) print("\(statusCode)") print(data ?? "no data") case .failure(_): break } } } 複製程式碼
-
自定義超時時間
public static func hFApiProvider(timeInterval:TimeInterval = 15) -> MoyaProvider<HFAPI> { return MoyaProvider<HFAPI>( requestClosure: { (endPoint, closure) in do { var urlRequest = try endPoint.urlRequest() urlRequest.timeoutInterval = timeInterval; closure(.success(urlRequest)) } catch MoyaError.requestMapping(let url) { closure(.failure(MoyaError.requestMapping(url))) } catch MoyaError.parameterEncoding(let error) { closure(.failure(MoyaError.parameterEncoding(error))) } catch { closure(.failure(MoyaError.underlying(error, nil))) } }) } 複製程式碼
-
錯誤處理
struct HFNetWork { public static func request(provider: MoyaProvider<HFAPI>, target: HFAPI, success successCallback: @escaping (JSON) -> Void, error errorCallback: @escaping (Int) -> Void, failure failureCallback: @escaping (MoyaError) -> Void) { provider.request(target) { result in switch result { case let .success(response): do { let json = try JSON(response.filterSuccessfulStatusCodes().mapJSON()) successCallback(json) } catch let error { errorCallback((error as! MoyaError).response!.statusCode) } case let .failure(error): failureCallback(error) } } } } 複製程式碼
-
呼叫
HFNetWork.request(provider: HFAPI.hFApiProvider(), target: .smscode(phone), success: { (json) in let jsonString = json.rawString() ?? "" if jsonString.count <= 0 { return } let responseObject = ResponseModel(JSONString: jsonString) guard let fResponseObject = responseObject else { return } HFLog.info(fResponseObject.data) }, error: { (errorcode) in }) { (error) in } } 複製程式碼