Xcode 错误对成员“dataTask(with:completionHandler:)”的不明确引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40728677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:36:10  来源:igfitidea点击:

Xcode Error Ambiguous reference to member 'dataTask(with:completionHandler:)'

xcodeswift3

提问by Jacob Blacksten

I have a swift 2.3 project I just updated to swift 3.0 and the following code broke.

我有一个 swift 2.3 项目,我刚刚更新到 swift 3.0 并且以下代码中断了。

    let task = URLSession.shared.dataTask(with: request, completionHandler: {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }

        print("response = \(response)")

        let responseString = NSString(data: data!, encoding: String.Encoding.utf8)
        print("responseString = \(responseString)")
    }) 
    task.resume()

I am unaware how to fix it

我不知道如何修复它

回答by Rob

You can get that error if the requestis a NSURLRequestrather than a URLRequest.

如果request是 aNSURLRequest而不是 a ,则可能会出现该错误URLRequest

let url = URL(string: urlString)!
let request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("error=\(error)")
        return
    }

    print("response = \(response)")

    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(responseString)")
}
task.resume()

Or, if you're mutating the URLRequest, use var:

或者,如果您正在改变URLRequest,请使用var

let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = ...

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("error=\(error)")
        return
    }

    print("response = \(response)")

    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(responseString)")
}
task.resume()

Also, note, I've replaced NSStringwith String.

另外,请注意,我已替换NSStringString.