Swift 3 开发快照中的 POST 请求给出了"对成员'dataTask(with:completionHandler:)'的模糊引用



我正在尝试在 Swift 3 开发快照中发出 POST 请求,但由于某种原因,对 NSURLSession.dataTask 的调用失败,标题中出现错误。

这是我正在使用的代码:

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, 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

谁能告诉我:

  1. 为什么给我这个错误
  2. 如何仅使用 Foundation 在最新的 Swift 开发快照中成功发出带有自定义参数的 POST 请求(我在任何情况下都无法使用其他第三方库)

谢谢!

编辑:我注意到有人在我的之后写了这个问题的副本。这里的答案是更好的。

>使用URLRequest结构。

在 Xcode8 中可以正常工作:

import Foundation
// In Swift3, use `var` struct instead of `Mutable` class.
var request = URLRequest(url: URL(string: "http://example.com")!)
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) {data, response, err in
    print("Entered the completionHandler")
}.resume()

此外,此错误的原因是URLSession API具有相同的名称方法,但每个方法采用不同的参数。

因此,如果没有显式强制转换,API 将被混淆。我认为这是 API 的命名错误。

出现此问题,以下代码:

let sel = #selector(URLSession.dataTask(with:completionHandler:))

请注意,从 Xcode 8.0 版本开始,URLSession.shared() 成为属性而不是方法,因此您必须将其称为 URLSession.shared.dataTask(with:);

最新更新