Maxim Tsybanov Maxim Tsybanov - 4 months ago 29
Swift Question

How to send POST parameters in Swift?

Here some code:

var URL: NSURL = NSURL(string: "http://stackoverflow.com")
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = ??????
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}


What should I write in
request.HTTPBody
if I want send POST query
"key" = "value"
?

Answer

No different than in Objective-C, HTTPBody expects an NSData object:

var bodyData = "key1=value&key2=value&key3=value"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

You'll have to setup the values & keys yourself in the string.