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

Problems with Swift3: cannot understand new syntax

昨天我更新到 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()
}

我得到这个错误:

Cannot invoke 'dataTask' with an argument list of type '(with: NSMutableURLRequest, completionHandler: (Data?, URLResponse?, NSError?) -> Void)'

请问有人帮我更正一下吗?

对于Swift3,勾选Apple Documentation就成功了,现在dataTask(with:completionHandler:) will take URLRequest as first argument and the completionHandler is changed to (Data?, URLResponse?, Error?) -> Void. So make instance of URLRequest instead of NSMutableURLRequest and made changes of completionHandler also. In Swift 3 with most of the public API they have changed NSError to 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
}