ios - 如何在 Xcode 7.0 (swift2.0) 中使用新的错误处理

标签 ios xcode swift2

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()
}

最佳答案

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

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

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

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

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

另请注意,nil options 参数变为空的 OptionSetType 文字(空括号),因为选项集在 Swift 2 中是实际的 .

但是等等……你仍然会在这里遇到编译错误,因为 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/

相关文章:

ios - 如何在 Xcode 中使用 C 代码进行优化

ios - 也可以快速从 TableView 和服务器中删除一行

ios - Swift 2 上的同步 URL 请求

ios - UITableView 中最后一个单元格丢失

ios - 将 curveEaseIn 添加到 Swift 动画

ios - 谷歌地图 - 3D View 是否可能

ios - 添加一个 UIButton 到 RootViewController 的 navigationBar

ios - 带有空UILabel的if语句

c - c 中的简单字符串列表正在泄漏内存(malloc 和 realloc)

ios - 带有 ios-charts 的特定柱上方的文本属性