参见英文答案 >
Swift 3 URLSession.shared() Ambiguous reference to member ‘dataTask(with:completionHandler:) error (bug)13个
我有一个swift 2.3项目我刚刚更新到swift 3.0并且以下代码中断了.
我有一个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()
我不知道如何解决它
解决方法
如果请求是NSURLRequest而不是URLRequest,则可以获得该错误.
let url = URL(string: urlString)! let request = URLRequest(url: url) let task = URLSession.shared.dataTask(with: request) { data,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,encoding: .utf8) print("responseString = \(responseString)") } task.resume()
另外,请注意,我已经用String替换了NSString.