Moya introduction

In short, Moya is a encapsulation of Alamofire, allowing developers to use Alamofire more elegantly.

Basic usage

  1. Define interface enumeration

    public enum HFAPI {
        case login(String.String.String) // Login interface
        case smscode(String)    // Log in and send the verification code
    }
    Copy the code
  2. Expand enumeration and implement TargetType, code details are as follows:

    extension HFAPI: TargetType {
        
        public var baseURL: URL {
            return URL.init(string: Interface domain name)! ; }public var path: String {
            switch self {
            case .login:
                return "Login interface path"
            case .smscode:
                return "Smscode Interface path"}}// The method used to request the interface
        public var method: Moya.Method {
            switch self {
            case .login:
                return .post
            case .smscode:
                return .get}}// Request parameters corresponding to the request interface
        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)}/ / the header information
        public var headers: [String : String]? {
            var header: [String:String] = [:]
            let token = HFDefault.getToken()
            if token.count > 0 {
                header["X-Token"] = token
            }
            return header
        }
        
        // for unit testing
        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()}}}Copy the code

    SampleData is used for unit testing. We can use Xcode’s own unit testing tools to test ourselves. For example:

    func testSmscodeAPI(a) {
            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}}}Copy the code
  3. You can customize the timeout period

     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)))}})}Copy the code
  4. Error handling

    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)
                }
            }
        }
    }
    Copy the code
  5. call

    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}}Copy the code