Home > OS >  Can't convert Alamofire request to Moya
Can't convert Alamofire request to Moya

Time:06-24

I have written an Alamofire request like below and get successful result.

let urlString = "https://dev.thebeats.app/api/authorization/send_signup_email?lang=en"
let url = URL(string: urlString)!

AF.request(url, method: .post,
                   parameters: ["email": "[email protected]"],
                   encoding: URLEncoding.default,
                   headers: ["Content-type": "application/x-www-form-urlencoded"],
                   interceptor: nil, requestModifier: nil)
            .response { result in
                print(String(decoding: result.data!, as: UTF8.self))
            }

Here is the response

{
    "status": 200,
    "success": true,
    "message": "Email send successfully",
    "body": {
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhbGciOiJIUzI1NiIsImlkIjo1Nywic3ViIjo1NywibmFtZSI6bnVsbCwiaWF0IjoxNjU1OTc5NTczLCJleHAiOjE2NTYwNjU5NzN9.331-g9WCEy6OIVkdm4UnxOx3BnuEx1fNy59shiYBgvQ"
    }
}

I have tried to write this request with Moya but always getting 404 error. Here is the code.

extension AuthenticationService: TargetType {
    var baseURL: URL {
        return URL(string: "https://dev.thebeats.app/api")!
    }
    
    var path: String {
        switch self {
        case .registration:
            return "/authorization/send_signup_email?lang=en"
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .registration:
            return .post
        }
    }
    
    var task: Task {
        switch self {
        case .registration(let email):
            var params: [String: Any] = [:]
                        params["email"] = "[email protected]"
            return .requestParameters(parameters: params, encoding: URLEncoding.default)
        }
    }
    
    var headers: [String : String]? {
        switch self {
        case .registration:
            return ["Content-type": "application/x-www-form-urlencoded"]
        }
    }
    
    var validationType: ValidationType {
        return .successCodes
    }
}

Here is the response using Moya

{
  "message": "Controller class Api could not be found.",
  "url": "/api/authorization/send_signup_email?lang=en",
  "code": 404,
  "file": "/var/www/html/vendor/cakephp/cakephp/src/Controller/ControllerFactory.php",
  "line": 340
}

Please help me to figure it out. Thanks in advance.

CodePudding user response:

You make it post , so this should be

    case .registration:
        return "/authorization/send_signup_email"

With

params["email"] = "[email protected]"
params["lang"] = "en"
  • Related