Swift3的问题:无法理解新语法

时间:2016-12-15 13:53:55

标签: xcode swift3 ios10 nsurlsessiondatatask xcode8.2

昨天我更新到Xcode 8.2,这迫使我更新到Swift 3.0语法。在我的应用程序中,我有这个功能:

func performGetRequest(_ targetURL: URL!, completion:@escaping (_ data: Data?, _ HTTPStatusCode: Int, _ error: NSError?) -> Void)
{
    let request = NSMutableURLRequest(url: targetURL)
    request.httpMethod = "GET"

    let sessionConfiguration = URLSessionConfiguration.default

    let Session = URLSession(configuration: sessionConfiguration)

    let tasksession = Session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
        if data != nil{
            DispatchQueue.main.async(execute: { () -> Void in
            completion(data: data, HTTPStatusCode: (response as! HTTPURLResponse).statusCode, error: error)})
        }
        else
        {
            print("Connection Lost")
        }

    })
    tasksession.resume()
}

我收到此错误:

  

无法调用' dataTask'使用类型'的参数列表(带:NSMutableURLRequest,completionHandler :(数据?,URLResponse?,NSError?) - > Void)'

拜托,有人会帮我纠正吗?

1 个答案:

答案 0 :(得分:2)

对于Swift 3,如果您选中Apple Documentation,则会发生罢工,现在dataTask(with:completionHandler:)URLRequest作为第一个参数,completionHandler更改为(Data?, URLResponse?, Error?) -> Void。因此,请设置URLRequest的实例而不是NSMutableURLRequest,并对completionHandler进行更改。在大多数公共API的Swift 3中,他们已将NSError更改为Error。如果你也使用Error,那就更好了。

func performGetRequest(_ targetURL: URL!, completion:@escaping (_ data: Data?, _ HTTPStatusCode: Int, _ error: Error?) -> Void) {

    let request = URLRequest(url: targetURL)
    request.httpMethod = "GET"

    let sessionConfiguration = URLSessionConfiguration.default

    let Session = URLSession(configuration: sessionConfiguration)

    let tasksession = Session.dataTask(with: request) { data, response, error in
        if data != nil{
            DispatchQueue.main.async {
                completion(data: data, HTTPStatusCode: (response as! HTTPURLResponse).statusCode, error: error)
            }
        }
        else
        {
            print("Connection Lost")
            DispatchQueue.main.async {
                completion(data: nil, HTTPStatusCode: (response as! HTTPURLResponse).statusCode, error: error)
            }
        }

    }
    tasksession.resume()
}

注意:您需要以所有可能的方式致电completionHendler,当您收到需要在其中调用的nil数据时,您尚未调用它else也使用nil作为数据值。

修改:您可以像这样调用此函数。

self.performGetRequest(url) { (data, status, error) in
    if error != nil {
        print(error?.localizedDescription)
        return
    }
    //Use data here
}