Furqan Muhammad Khan Furqan Muhammad Khan - 6 months ago 79
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)
})
task.resume()
}


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.

Answer

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.