OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 Xcode 7.0 (swift2.0) 中使用新的错误处理 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 09:06
标题: ios - 如何在 Xcode 7.0 (swift2.0) 中使用新的错误处理

swift 2.0 的错误处理是不同的,当尝试设置 NSURL session 并使用完成处理程序时,错误参数在 swift 1.2 中可用,但是在查看文档时,错误参数不再存在,并且它试图告诉我改用抛出函数语句,而不是真正熟悉语法。 block 引号是错误消息出现的地方,此代码在 Xcode 6.4 或更早版本中运行良好,但不适用于 7.0

/Volumes/MyData/AppDevXcode7/Training/iOS8.0Dev/connecting_swift/connecting_swift/JSONViewController.swift:28:78: Invalid conversion from throwing function of type '(_, _, _) throws -> _' to non-throwing function type '(NSData?, NSURLResponse?, NSError?) -> Void'

@IBAction func callURLButtonTapped(sender: AnyObject){
    urlTextField.resignFirstResponder()
    let requestedURL = NSURL(string: urlTextField.text!)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(requestedURL!, completionHandler: {data, response, error in
            if let actualError = error {
                let errorResponse = "Response status: \(actualError.description)"
                self.responseText.text = errorResponse
            }else{
                var parseError: NSError?
                let jsonArray = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError ) as! NSDictionary

                    if let actualParseError = parseError {
                        let errorResponse = "Response status: \(actualParseError.description)"
                        self.responseText.text = errorResponse
                    }else{
                        dispatch_async(dispatch_get_main_queue(), {
                            let httpResponse = response as! NSHTTPURLResponse
                            let responseStatus = "Response status: \(httpResponse.statusCode)"
                            self.responseStatusLabel.text = responseStatus
                            let responseAsString = jsonArray.description
                            self.responseText.text = responseAsString
                        })
                    }

                }
    })
    task.resume()
}



Best Answer-推荐答案


当前 Swift 编译器中的错误消息并不总是表明问题的根本原因。 (特别是在这种情况下,在传递给某个函数的闭包深处存在类型检查错误,它会给出关于闭包函数而不是根本原因的错误消息。)File bugs当您看到这些类型的错误时,Apple 可以更好地提供良好的错误消息。

在这里,新的错误处理语法存在问题是正确的,但它的位置错误(因为嵌套的闭包)。 您的问题出在这一行:

let jsonArray = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError ) as! NSDictionary

NSJSONSerialization.JSONObjectWithData(_ptions:error 调用是在 Swift 2.0 中变成 throws 函数的方法之一。所以你需要这样调用它:

let jsonArray = try NSJSONSerialization.JSONObjectWithData(data, options: [] ) as! NSDictionary

还要注意 nil options 参数变成了一个空的 OptionSetType 文字(空括号),因为选项集是 Swift 2 中的实际 sets .

但是等等……你仍然会在这里得到一个编译错误,因为 data 是一个可选的,必须检查/解包。你需要一个合适的地方来处理你的错误。让我们修改此方法以在正确的位置处理所有内容:

@IBAction func callURLButtonTapped(sender: AnyObject){
    urlTextField.resignFirstResponder()
    let requestedURL = NSURL(string: urlTextField.text!)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(requestedURL!, completionHandler: {data, response, error in
        // First, make sure we have real data, and handle the error if not.
        // (That's a better use of the API contract than checking the error parameter, because the error parameter is not guaranteed to be non-nil in all cases where correct data is received.)
        // Use a guard clause to keep the "good path" less indented.
        guard let actualData = data else {
            self.responseText.text = "Response status: \(error!.description)"
            return
        }
        do {
            // Use do/try/catch to call the new throwing API.
            // Use the new OptionSetType syntax, too.
            let jsonArray = try NSJSONSerialization.JSONObjectWithData(actualData, options: [])
            dispatch_async(dispatch_get_main_queue(), {
                let httpResponse = response as! NSHTTPURLResponse
                self.responseStatusLabel.text = "Response status: \(httpResponse.statusCode)"
                self.responseText.text = jsonArray.description
            })
        } catch let parseError {
            // No need to treat as NSError and call description here, because ErrorTypes are guaranteed to be describable.
            self.responseText.text = "Response status: \(parseError)"
        }
    })
    task.resume()
}

关于ios - 如何在 Xcode 7.0 (swift2.0) 中使用新的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31490485/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4