我正在尝试在
Swift 3开发快照中发出POST请求,但由于某种原因,对NSURLSession.dataTask的调用失败,标题中出现错误.
@H_502_19@这是我正在使用的代码:
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()
错误正是:
testy.swift:19:12: error: ambiguous reference to member 'dataTask(with:completionHandler:)' var task = session.dataTask(with: request,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,NSError?) -> Swift.Void) -> NSURLSessionDataTask
谁能告诉我:
>为什么它给了我这个错误
>如何使用仅基于最新的Swift开发快照在自定义参数中成功发出POST请求(在任何情况下我都无法使用其他第三方库)
谢谢!
编辑:我注意到有人在我之后写了这个问题的副本.这里的答案是更好的答案.