Search code examples
swiftalamofireswift5

How to parse JSON response to Model struct from Alamofire in Swift 5?


I try to post mysql database with Alamofire and I succeed but my response is not seems json and I want to pass response values to model struct. I tried this code. Where is the wrong ? I would be very grateful if you can help.

 func register(registerModel:RegisterResponse,completion:@escaping (RegisterModel?)->() ){
    let parameters: [String: Any] =
    [
        "email": "\(registerModel.email)",
        "password": "\(registerModel.password)",
        "first_name": "\(registerModel.first_name)",
        "last_name": "\(registerModel.last_name)",
    ]
   
    AF.request(registerUrl,method: .post,parameters: parameters,encoding: URLEncoding.httpBody,headers: nil).responseJSON(){ response in
       //debugPrint(response)
        switch response.result{
        
        case .success(let data):
        
                if response.data != nil {
                    
                    print(data)
                    completion(data as? RegisterModel)
                    
                }
            
          
        case .failure(let err):
            print(err.localizedDescription)
        }
    }
    
}

output:

{
result = "account already exists";
tf = 0;
verificationCode = "<null>";
}

Solution

  • Assuming your RegisterResponse is Decodable, simply use responseDecodable:

    AF.request(registerUrl, method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
      .responseDecodable(of: RegisterResponse.self) { response in
        // Handle response.
      }