Swift 3 URLSession.shared()成员'dataTask(with:completionHandler :)的引用不正确(bug)


169

您好,我有swift2.2的json解析代码,但是当我将其用于Swift 3.0时,出现了该错误

ViewController.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()

感谢您的想法。


2
我得到了同样的错误,因为我传递一个字符串dataTask(with:如我url = "www.yahoo.com和我经过它直冲功能,而无需将其转换为一个URL
蜂蜜

Answers:


312

函数签名使编译器感到困惑。您可以这样解决:

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

但是,请注意,如果早先声明为而不是,则我们不必像URLRequest在此签名中那样强制转换“ request” :URLRequestNSMutableURLRequest

var request = URLRequest(url:myUrl!)

这是NSMutableURLRequest新的之间的自动转换,而新的自动转换URLRequest失败了,这迫使我们在此进行转换。


7
var request = URLRequest(url:myUrl!)
Leo Dabus

1
SE-0072说,删除隐式桥接。当“ swifty函数名称”成为“事实上的重写方法”时,我们无法反向查找Objective-C SEL,因此必须使用或强制转换为Foundation结构。
quesera2 '16

2
非常有帮助的答案。我只补充说,避免myUrl会很好!通过执行以下操作强制展开:guard let myUrl = URL(string:listUrlString)else {return}然后可以在不使用!的情况下调用请求!var request = URLRequest(url:myUrl)
Mark Semsel

2
在可以URL(string:)构造任何故障?
BallpointBen

得投票,但我仍然有问题,任何人都会输出“字符0周围的无效值”?
马芬。F

33

您将init设置myRequestNSMutableURLRequest,您需要这样做:

var URLRequest

斯威夫特放弃了这两个NSMutable...东西。仅var用于新类。


17

Xcode 8和Swift 3.0

使用URLSession:

 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()

URLSession委托调用:

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%结果保证


15

造成此问题的原因是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
}

确实有道理。谢谢
iBug

10

就我而言,错误是在NSURL中

let url = NSURL(string: urlString)

在Swift 3中,您必须只写URL

let url = URL(string: urlString)

3

经过测试的xcode 8稳定版本; 需要使用var requestwith URLRequest()thats 变量,您可以轻松地解决该问题(bug

var request = URLRequest(url:myUrl!)

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

工作正常!谢谢大家,我认为对很多人都有帮助。!


1
从URLRequest转换为URLRequest没有意义
Leo Dabus

var request = URLRequest(url: url); let task = URLSession.shared().dataTask(with: request) { ... }
Leo Dabus

shared是Swift 3中的属性而不是函数(不带括号)。
vadian

@vadian当时我未发布评论
Leo Dabus

3

对于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

在Swift 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

3

简明扼要的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()

2
 // 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()

2

要通过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) { ...

2
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()

2

Xcode 10.1 Swift 4

这对我有用:

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

关键是添加URLSessionDataTask类型声明。


1

对我来说,这样做是为了

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

不能使用

"let url = NSURL(string: urlString)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.