I am trying to make a POST request in a Swift 3 development snapshot, but for some reason the NSURLSession.dataTask call failed with a header error.
Here is the code I'm using:
import Foundation var err: NSError? var params: Dictionary<String, String> var url: String = "http://notreal.com" var request = NSMutableURLRequest(url: NSURL(string: url)!) var session = NSURLSession.shared() request.httpMethod = "POST" request.httpBody = try NSJSONSerialization.data(withJSONObject: params, options: []) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var task = session.dataTask(with: request, completionHandler: {data, response, err -> Void in print("Entered the completionHandler") }) task.resume()
Error in accuracy:
testy.swift:19:12: error: ambiguous reference to member 'dataTask(with:completionHandler:)' var task = session.dataTask(with: request, completionHandler: {data, response, err -> Void in ^~~~~~~ Foundation.NSURLSession:2:17: note: found this candidate public func dataTask(with request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Swift.Void) -> NSURLSessionDataTask ^ Foundation.NSURLSession:3:17: note: found this candidate public func dataTask(with url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Swift.Void) -> NSURLSessionDataTask
Can anyone tell me:
- Why does this give me this error.
- How to successfully make a POST request with custom parameters in the last Swift development snapshot using only Foundation (I cannot use other third-party libraries under any circumstances)
Thanks!
Edit: I note that someone wrote a duplicate of this question after mine. The answer here is the best.
post swift nsurlsession macos
Chuppa chump
source share