1

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

我得到这个错误:

无法使用类型为“(带有:NSMutableURLRequest,completionHandler:(Data?,URLResponse?,NSError?)-> Void)”类型的参数列表调用“dataTask”

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

4

1 回答 1

2

对于 Swift 3,如果你检查它是 batte Apple Documentation,NowdataTask(with:completionHandler:)URLRequest作为第一个参数,并且completionHandler更改为(Data?, URLResponse?, Error?) -> Void. 所以用实例URLRequest代替而不是也NSMutableURLRequest改变了completionHandler。在带有大部分公共 API 的 Swift 3 中,它们已更改NSErrorError. 所以如果你也使用面糊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
}
于 2016-12-15T14:41:10.447 回答