life4
life4

Reputation: 75

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>";
}

Upvotes: 1

Views: 1888

Answers (2)

Jon Shier
Jon Shier

Reputation: 12770

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.
  }

Upvotes: 2

Mohamad Kaakati
Mohamad Kaakati

Reputation: 388

Try this

AF.request(registerUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default) .responseJSON { (response) in
    print(response)
}

Upvotes: 1

Related Questions