Xcode Error对成员’dataTask(with:completionHandler :)’的模糊引用

前端之家收集整理的这篇文章主要介绍了Xcode Error对成员’dataTask(with:completionHandler :)’的模糊引用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Swift 3 URLSession.shared() Ambiguous reference to member ‘dataTask(with:completionHandler:) error (bug)13个
我有一个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.

原文链接:https://www.f2er.com/iOS/329085.html

猜你在找的iOS相关文章