Reputation: 39
For a POST request, I use this code:
private func post(url: String, params: [String: AnyObject], headers: [String: AnyObject]) {
let url = NSURL(string: apiUrl)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Application")
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
} catch {
print("error")
//POST with completionHandler
var task = session.dataTaskWithRequest(url, completionHandler: { (data, response, error) -> Void in
print(data)
})
}
}
and at the line that startst with var task = ...
I get this error: Cannot convert value of type 'NSURL' to expected argument type 'NSURLRequest'
Upvotes: 0
Views: 2796
Reputation: 19750
change this line:
var task = session.dataTaskWithRequest(url, completionHandler: { (data, response, error) -> Void in
and pass in the request... not the url:
var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
Always read the method name you are calling, this is specifically creating a dataTaskWith a REQUEST, xcode should of also highlighted this.
Upvotes: 1