Hi i'm trying to replicate the following curl command in swift using NSURLSession in a playground.
curl -k -i -H "Accept: application/json" -H "X-Application: " -X POST -d 'username=&password=' https://address.com/api/login
Here's what I've got so far. Where i'm struggling is that i'm unsure how to send the post data e.g.: 'username=&password='. Any help would be appreciated.
Thanks in advance.
import Foundation
import XCPlayground
// Let asynchronous code run
XCPSetExecutionShouldContinueIndefinitely()
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["Accept" : "application/json", "X-Application" : "<AppKey>"]
let session = NSURLSession(configuration: config)
var running = false
let url = NSURL(string: "https://address.com/api/login")
let task = session.dataTaskWithURL(url!) {
(let data, let response, let error) in
if let httpResponse = response as? NSHTTPURLResponse {
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString)
}
running = false
}
running = true
task.resume()
You can create a mutable
URLRequest
and set thehttpBody
. But you should also percent escape the values forusername
and, more importantly, forpassword
.So, imagine your request being created like so:
So the question is how
setBodyContent
builds the request body given a dictionary. Yes, you want to percent-escape anything not in the unreserved character set, but sadlyCharacterSet.urlQueryAllowed
is not up to the job. So you might do something like:Furthermore, I generally use a more complicated
setBodyContent
that also accepts numeric, boolean, and date types, but I didn't want to digress too far from your core question, how to properly build request for two string key/values pairs.For Swift 2 rendition, see previous revision of this answer.
maybe this help, i use it to send post data:
NSUTF8StringEncoding can be replaced with whatever you need