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
Xcode Error Ambiguous reference to member 'dataTask(with:completionHandler:)'
提问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 request
is a NSURLRequest
rather 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 NSString
with String
.
另外,请注意,我已替换NSString
为String
.