Swift 3 URLSession.share ()对成员‘ dataTask 的模糊引用(带有: CompletionHandler:) error (bug)

您好,我已经为 Swift 2.2编写了 json 解析代码,但是当我在 Swift 3.0中使用它时,出现了这个错误

Swift: 132:31: 对成员‘ dataTask (with: CompletionHandler:)’的模糊引用

这是我的密码

   let listUrlString =  "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex)
let myUrl = URL(string: listUrlString);
let request = NSMutableURLRequest(url:myUrl!);
request.httpMethod = "GET";


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


if error != nil {
print(error!.localizedDescription)
DispatchQueue.main.sync(execute: {
AWLoader.hide()
})


return
}


do {


let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray


if let parseJSON = json {


var items = self.categoryList


items.append(contentsOf: parseJSON as! [String])


if self.fromIndex < items.count {


self.categoryList = items
self.fromIndex = items.count


DispatchQueue.main.async(execute: {


self.categoriesTableView.reloadData()


AWLoader.hide()


})
}else if( self.fromIndex == items.count){




DispatchQueue.main.async(execute: {


AWLoader.hide()


})


}






}


} catch {
AWLoader.hide()
print(error)


}
}


task.resume()

谢谢你的建议。

109608 次浏览

编译器被函数签名搞糊涂了,你可以这样修复它:

let task = URLSession.shared.dataTask(with: request as URLRequest) {

但是,请注意,我们不必在这个签名 如果中将“ request”强制转换为 URLRequest,它在早些时候被声明为 URLRequest而不是 NSMutableURLRequest:

var request = URLRequest(url:myUrl!)

这是自动铸造之间的 NSMutableURLRequest和新的 URLRequest是失败的,这迫使我们在这里进行铸造。

你已经将 myRequest初始化为 NSMutableURLRequest,你需要这个:

var URLRequest

斯威夫特正在抛弃 NSMutable...的东西。只是使用 var的新类。

测试了 xcode 8稳定版; 需要在 URLRequest()中使用 var request变量

var request = URLRequest(url:myUrl!)

let task = URLSession.shared().dataTask(with: request as URLRequest) { }

工作很好! 谢谢你们,我想帮助了很多人!

此问题是由 URLSession 有两个 dataTask 方法引起的

open func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask
open func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask

第一个方法使用 URLRequest作为参数,第二个方法使用 URL作为参数,因此我们需要指定要调用的类型,例如,我想调用第二个方法

let task = URLSession.shared.dataTask(with: url! as URL) {
data, response, error in
// Handler
}

Xcode 8和 Swift 3.0

使用网址会话:

 let url = URL(string:"Download URL")!
let req = NSMutableURLRequest(url:url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)


let task : URLSessionDownloadTask = session.downloadTask(with: req as URLRequest)
task.resume()

代表呼叫:

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {


}




func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
print("downloaded \(100*writ/exp)" as AnyObject)


}


func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){


}

使用块 GET/POST/PUT/DELETE:

 let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval:"Your request timeout time in Seconds")
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers as? [String : String]


let session = URLSession.shared


let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
let httpResponse = response as? HTTPURLResponse


if (error != nil) {
print(error)
} else {
print(httpResponse)
}


DispatchQueue.main.async {
//Update your UI here
}


}
dataTask.resume()

对我来说工作很好。试一下100% 的结果保证

 // prepare json data
let mapDict = [ "1":"First", "2":"Second"]


let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData


// create post request
let url = NSURL(string: "http://httpbin.org/post")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"


// insert json data to the request
request.httpBody = jsonData as Data




let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
return
}
do {
let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]


print("Result",result!)


} catch {
print("Error -> \(error)")
}
}


task.resume()

要通过 GET 请求加载数据,不需要任何 URLRequest(也不需要分号)

let listUrlString =  "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex)
let myUrl = URL(string: listUrlString)!
let task = URLSession.shared.dataTask(with: myUrl) { ...

对我来说,我这样做是为了找到,

let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in ...}

不能用

"let url = NSURL(string: urlString)

对于 Swift 3和 Xcode 8:

      var dataTask: URLSessionDataTask?


if  let url = URL(string: urlString) {
self.dataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in


if let error = error {
print(error.localizedDescription)
} else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
// You can use data received.
self.process(data: data as Data?)
}
})
}
}

//注意: 始终可以使用调试器检查错误

在迅捷3中,编译器被函数签名搞糊涂了。指定它将清除错误。还将 URL 字符串转换为 URL 类型。下面的代码对我很有用。

   let urlString = "http://bla.com?batchSize="
let pathURL = URL(string: urlString)!
var urlRequest = URLRequest(url:pathURL)


let session = URLSession.shared
let dataTask = session.dataTask(with: urlRequest as URLRequest) { (data,response,error) in
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data,response,error in
if error != nil{
print(error!.localizedDescription)
return
}
if let responseJSON = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String:AnyObject]{
if let response_token:String = responseJSON["token"] as? String {
print("Singleton Firebase Token : \(response_token)")
completion(response_token)
}
}
})
task.resume()

Swift 3的简短回答:

guard let requestUrl = URL(string: yourURL) else { return }


let request = URLRequest(url:requestUrl)
URLSession.shared.dataTask(with: request) {
(data, response, error) in
...


}.resume()

在我的案例中,错误出现在 NSURL

let url = NSURL(string: urlString)

在 Swift 3中,你必须只写 网址:

let url = URL(string: urlString)

Xcode 10.1 Swift 4

这对我很有效:

let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
...

键是在 URLSessionDataTask类型声明中添加。