Xcode错误对成员'dataTask的歧义引用(with:completionHandler :)'
问题描述:
我有一个swift 2.3项目,我刚更新到swift 3.0,下面的代码破坏了。Xcode错误对成员'dataTask的歧义引用(with:completionHandler :)'
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()
,我不知道如何解决它
答
你可以得到错误,如果request
是NSURLRequest
而非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()
或者,如果你的变异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()
此外,请注意,我把它换成NSString
与String
。