Swift 3 URLSession.shared()对成员'dataTask(with:completionHandler :)的错误引用错误(bug)

Swi*_*per 162 json ios swift3

你好我有工作json解析swift2.2的代码,但当我用它为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()
Run Code Online (Sandbox Code Playgroud)

谢谢你的想法.

aya*_*aio 307

编译器被函数签名搞糊涂了.你可以像这样解决它:

let task = URLSession.shared.dataTask(with: request as URLRequest) {
Run Code Online (Sandbox Code Playgroud)

但是,请注意,如果之前声明的是,我们不必像URLRequest在此签名中那样强制转换"请求" ,而不是:URLRequestNSMutableURLRequest

var request = URLRequest(url:myUrl!)
Run Code Online (Sandbox Code Playgroud)

这是失败之间的自动投射NSMutableURLRequest和新URLRequest的失败,这迫使我们在这里进行这种投射.

  • `var request = URLRequest(url:myUrl!)` (7认同)
  • 非常有用的答案.我只想补充说,避免使用myUrl会很好!通过执行以下操作强制解包:guard let myUrl = URL(string:listUrlString)else {return}然后可以在没有!的情况下调用请求!var request = URLRequest(url:myUrl) (2认同)
  • `URL(string:)`构造函数是否会失败? (2认同)

Hen*_*Two 33

你已经初始化myRequestNSMutableURLRequest,你需要这个:

var URLRequest
Run Code Online (Sandbox Code Playgroud)

斯威夫特正在抛弃这两NSMutable...件事.只需var用于新课程.

  • 谢谢一个男人.这是完美的解决方案.干杯! (2认同)

Sau*_*hah 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()
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

使用Block 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()
Run Code Online (Sandbox Code Playgroud)

对我来说工作正常..试试100%结果保证


小智 12

这个问题是由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
Run Code Online (Sandbox Code Playgroud)

第一个有URLRequest参数,第二个有URL参数,所以我们需要指定要调用的类型,例如,我想调用第二个方法

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


Zha*_*rik 9

在我的情况下错误是在NSURL

let url = NSURL(string: urlString)
Run Code Online (Sandbox Code Playgroud)

在Swift 3中,您必须只写一个URL:

let url = URL(string: urlString)
Run Code Online (Sandbox Code Playgroud)