How to send a POST request with BODY in swift How to send a POST request with BODY in swift json json

How to send a POST request with BODY in swift


If you are using Alamofire v4.0+ then the accepted answer would look like this:

let parameters: [String: Any] = [    "IdQuiz" : 102,    "IdUser" : "iosclient",    "User" : "iosclient",    "List": [        [            "IdQuestion" : 5,            "IdProposition": 2,            "Time" : 32        ],        [            "IdQuestion" : 4,            "IdProposition": 3,            "Time" : 9        ]    ]]Alamofire.request("http://myserver.com", method: .post, parameters: parameters, encoding: JSONEncoding.default)    .responseJSON { response in        print(response)    }


You're close. The parameters dictionary formatting doesn't look correct. You should try the following:

let parameters: [String: AnyObject] = [    "IdQuiz" : 102,    "IdUser" : "iosclient",    "User" : "iosclient",    "List": [        [            "IdQuestion" : 5,            "IdProposition": 2,            "Time" : 32        ],        [            "IdQuestion" : 4,            "IdProposition": 3,            "Time" : 9        ]    ]]Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON)    .responseJSON { request, response, JSON, error in        print(response)        print(JSON)        print(error)    }

Hopefully that fixed your issue. If it doesn't, please reply and I'll adjust my answer accordingly.


I don't like any of the other answers so far (except perhaps the one by SwiftDeveloper), because they either require you to deserialize your JSON, only for it to be serialized again, or care about the structure of the JSON itself.

The correct answer has been posted by afrodev in another question. You should go and upvote it.

Below is just my adaption, with some minor changes (primarily explicit UTF-8 charset).

let urlString = "https://example.org/some/api"let json = "{\"What\":\"Ever\"}"let url = URL(string: urlString)!let jsonData = json.data(using: .utf8, allowLossyConversion: false)!var request = URLRequest(url: url)request.httpMethod = HTTPMethod.post.rawValuerequest.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")request.httpBody = jsonDataAlamofire.request(request).responseJSON {    (response) in    print(response)}