【问题标题】:POST request in Swift 3 dev snapshot gives "ambiguous reference to member 'dataTask(with:completionHandler:)'Swift 3 开发快照中的 POST 请求给出了“对成员 'dataTask(with:completionHandler:)' 的模糊引用
【发布时间】:2016-05-30 15:17:17
【问题描述】:

我正在尝试在 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 请求(在任何情况下我都无法使用其他第三方库)

谢谢!

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

【问题讨论】:

  • 这很奇怪,我不明白为什么传递 NSMutableURLRequest 是模棱两可的。它不是 NSURL 的子类,所以 IDK 它会如何认为它可以进入那里。
  • 这就是我的想法。它可能是一个错误,因为它是开发快照。
  • 您可以尝试通过将 dataTaskWithRequest:completionHandler: 分配给具有指定类型注释的变量 (NSURL, (NSData?, NSURLResponse?, NSError?) -&gt; Swift.Void) -&gt; NSURLSessionDataTask 然后调用该闭包来消除此调用的歧义

标签: swift macos post nsurlsession


【解决方案1】:

使用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:))

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2016-10-15
      • 2023-03-25
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 2018-04-02
      相关资源
      最近更新 更多