Furqan Muhammad Khan Furqan Muhammad Khan - 8 months ago 96
Swift Question

Answered: iOS9 + Swift: How To Set The Body of A Post Request Using a JSON Value?

I am trying to make an HTTP Post request to a development server with self signed certificate. This is the function making the POST call:

func makeHTTPPostRequest(path: String, body: JSON, onCompletion: (JSON?, NSError?) -> Void) {

let request = NSMutableURLRequest(URL: NSURL(string: path)!)
request.HTTPMethod = "POST"

// I am using SwiftyJSON
do {
request.HTTPBody = try body.rawData()
} catch _ { }

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var json: JSON?
if let _data = data {
json = JSON(data: _data)
onCompletion(json, error)

When I make a POST request, the server returns me "Empty fields" error even though I have properly set the HTTPBody of the request:

enter image description here

PS: The route is working fine when I call it from Postman.

EDIT: Irrelevant parts of the question removed.


The request.HTTPBody property must be a NSData object. If you want to send JSON, the data object should contain a sequence of Unicode characters (preferable UTF-8) which is your serialised JSON representation.

Additionally, you should also set the Content-Type header accordingly to application/json.