1
votes

I am trying to send POST HTTP request with body using Alamofire and would appreciate any help.

My body:

{"data":{"gym":{"country":"USA","city":"San Diego","id":1}}}

Should I do something like this?

let parameters: [String: Any] = [ "data": [
  "gym": [
  "country":"USA",
  "city":"San Diego",
  "id":1
]]]

Alamofire.request(URL, method: .post, parameters: parameters, headers: headers())
  .responseJSON { response in
    print(response)
} 
4
what issue are you facingHussain Chhatriwala
I think you need to pass json as parameter in request body, try to convert parameters in json data n pass in request bodyPratik Prajapati
so the server says that it is not valid, however when I do it in postman this works fineAlex Schanz

4 Answers

2
votes

If you wish to send the parameters in json format use encoding as JSONEncoding. So add parameter for encoding in request as follows:

Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers())
   .responseJSON { response in
    print(response)
} 

Hope it helps...

0
votes

Try this method to convert your json string to dictionary

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

let str = "{\"data\":{\"gym\":{\"country\":\"USA\",\"city\":\"San Diego\",\"id\":1}}}"

let dict = convertToDictionary(text: str)

and send dictionary as a param in your request.

Alamofire.request(URL, method: .post, parameters: dict, headers: headers())
  .responseJSON { response in
    print(response)
} 

ref : How to convert a JSON string to a dictionary?

0
votes

What I think is that you should try and prepare your dictionary in the this format:

var gym = [String:Any]()
gym["country"] = "USA"
gym["city"] = "San"

var data = [[String:Any]]()
data.append(gym)
var metaData = [String:Any]()
metaData["data"] = data
0
votes

Your parameters is wrong...

let parameters: [String: Any] = { "data": 
  {
    "gym": {
      "country":"USA",
      "city":"San Diego",
      "id":1
    }
  }
}

Alamofire.request(<YOUR-URL>,
                      method: .post,
                      parameters: parameters,
                      encoding: URLEncoding(destination: .queryString),
                      headers: <YOUR-HEADER>
      ).validate().responseString { response in
      switch response.result {
      case .success:

        debugPrint("Good to go.")
        debugPrint(response)

      case .failure:

        let errMsg = String(data: response.data!, encoding: String.Encoding.utf8)!
        debugPrint(errMsg)
        debugPrint(response)

      }
    }

Hope this help. BTW, in Alamofire 5, debugPrint(response) can print out response.data directly.