0

I am using Alamofire 5. I have put the parameters to httpbody. I have run it in Postman, and it is working fine. My body parameters are below.

{
"user_id": "user_id",
"username": "user_name",
"password": "pass",
"token": "",
"type_id": 100,
"country_id": 1,
"language_id": 1,
"customer_id": 1,
"parent_user_id": "",
"profile": {}
 }

I have used below code to put the request using Alamofire 5. Here is the code:

func change_password() {

let headers: HTTPHeaders = [
    "Content-Type": "application/json",
    "YumaSession": Global_Variable.globalValue.session_id
]
let parameters:Parameters = [
    "user_id": "user_id",
    "username":  "username",
    "password": txtPassword.text!,
    "token": "",
    "type_id": 100,
    "country_id": 1,
    "language_id": 1,
    "customer_id": 1,
    "parent_user_id": "",
    "profile": []
]

AF.request( url,method: .put,parameters: parameters,encoding: URLEncoding.httpBody,headers: headers).responseJSON{ response in

    switch response.result {
    case .success(let responseData):
        print("responseData-->",response.response!.statusCode)
    case .failure(let error):
        print("error--->",error)
    }
    }
   }

Above code returns 500 status code. What is wrong above the code?

Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93
Enamul Haque
  • 4,789
  • 1
  • 37
  • 50
  • You can tell POSTMAN to generate the equivalent request in CURL and use feature in Alamofire to print the request as a CURL one (cf. there https://stackoverflow.com/questions/53637437/alamofire-with-d/53637821#53637821) and compare the two codes. You'll be able to spot a difference. But `URLEncoding.httpBody`, as URLEncoded? Or JSONEncoded? – Larme Dec 31 '19 at 16:13
  • 1
    The `profile` field is a dictionary in the postman body and an array in your AF parameters. Also is the server telling you why it’s returning 500 in the response body? – Warren Burton Dec 31 '19 at 16:16
  • @WarrenBurton how to write in profile field? – Enamul Haque Dec 31 '19 at 16:19
  • 1
    `"profile": [:]` – Larme Dec 31 '19 at 16:22
  • @Larme Thanks it is working fine – Enamul Haque Dec 31 '19 at 16:25

1 Answers1

1

parameters.profile is defined with an array literal instead of an dictionary one. Fixed code below.

let parameters:Parameters = [
    "user_id": "user_id",
    "username":  "username",
    "password": txtPassword.text!,
    "token": "",
    "type_id": 100,
    "country_id": 1,
    "language_id": 1,
    "customer_id": 1,
    "parent_user_id": "",
    "profile": [:]
]
Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93