Swift 2.0:Xcode 7 中的 HTTP GET 错误处理

Swift 2.0: HTTP GET error handling in Xcode 7

我是 xcode 编程新手,我正在尝试在 Swift 2 中实现一个发出 HTTP Get 请求的应用程序。升级后 xcode 7 显示错误:

Cannot convert value of type 
'(NSData!, response: NSURLResponse!, err: NSError!) -> ()'
to expected argument type 
'(NSData?, NSURLResponse?, NSError?) -> Void'

(此代码片段使用 swift 1.2 的旧错误处理。)任何人都可以帮助我如何在 Swift 2.0.

中实现它
    request.HTTPMethod = "GET"
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(request, completionHandler:loadedData)

    task.resume()


}

func loadedData(data:NSData!, response:NSURLResponse!, err:NSError!){

    if(err != nil)
    {
        print(err?.description)
    }
    else
    {
        var jsonResult: NSDictionary = NSDictionary()
        let httpResponse = response as! NSHTTPURLResponse
        print("\(httpResponse.statusCode)")

        if (httpResponse.statusCode == 200)
        {

            jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
            print(jsonResult)


            self.performSegueWithIdentifier("SuccessSignin", sender: self)

        }
        else if (httpResponse.statusCode == 422){

            print("422 Error Occured...")
        }


    }

}

这是您收到的错误消息:

Cannot convert value of type 
'(NSData!, response: NSURLResponse!, err: NSError!) -> ()'
to expected argument type 
'(NSData?, NSURLResponse?, NSError?) -> Void'

如消息中所示,dataTaskWithRequestcompletionHandler 的参数已从 强制展开 (!) 更改只是 optionals (?)。

注意 !?:

// old
(NSData!, response: NSURLResponse!, err: NSError!)
// new
(NSData?, NSURLResponse?, NSError?)

因此,您需要相应地调整代码。

例如,您的方法声明如下所示:

func loadedData(data:NSData?, response:NSURLResponse?, err:NSError?)

此外,评估方法主体并确保您现在正确解包可选参数 dataresponseerr

有关详细信息,请参阅 NSURLSession class 参考。

方法签名已更改(参数现在是可选的)。此外,您必须使用包含在 do catch 块中的 try。并避免使用强制尝试(使用 !)但更喜欢捕获可能的错误,并使用 if let 安全地解包可选值。示例:

let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
    if error != nil {
        print(error!.description)
    } else {
        if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                do {
                    if let data = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
                        print(jsonResult)
                        self.performSegueWithIdentifier("SuccessSignin", sender: self)
                    }
                } catch let JSONError as NSError {
                    print(JSONError)
                }
            } else if (httpResponse.statusCode == 422) {
                print("422 Error Occured...")
            }
        } else {
            print("Can't cast response to NSHTTPURLResponse")
        }
    }
}

task.resume()