【问题标题】:how to use new error handling with Xcode 7.0 (swift2.0)如何在 Xcode 7.0 (swift2.0) 中使用新的错误处理
【发布时间】:2015-07-18 11:03:07
【问题描述】:

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

/Volumes/MyData/AppDevXcode7/Training/iOS8.0Dev/connecting_swift/connecting_swift/JSONViewController.swift:28:78:从 '(_, _, _) throws -> _' 类型的抛出函数到非的无效转换- 抛出函数类型 '(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()
}

【问题讨论】:

    标签: ios xcode swift2


    【解决方案1】:

    当前 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 中的实际 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()
    }
    

    【讨论】:

      【解决方案2】:

      在 Swift 2、XCode 7 中,Apple 将 NSError 替换为 ErrorType。

      您在自己的代码中明确使用 NSError。这在大多数情况下都有效(例如分配),但并非全部有效。 用 ErrorType 替换你自己的 NSError 用法。

      【讨论】:

        猜你喜欢
        • 2015-09-08
        • 1970-01-01
        • 2023-03-14
        • 2011-04-02
        • 2012-06-16
        • 2010-12-14
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多