【问题标题】:Swift 2 JSON Call can throw, but it is not marked with 'try' and the error is not handledSwift 2 JSON Call 可以抛出,但它没有用'try'标记并且错误没有被处理
【发布时间】:2016-01-24 02:50:23
【问题描述】:

我有一个名为recognizeDropoff 的函数,它在Xcode 6.4 中与Swift 1.2 配合得很好。但是,现在我将 Xcode 7.1 与 Swift 2 一起使用,我收到了这个错误:Call can throw, but it is not marked with 'try' and the error is not handled

func recognizeDropoff() {
        let currentUsername = PFUser.currentUser()!.username

        let url = NSURL(string: "http://test.informatica-corlaer.nl/dropoffRecognizer.php?user=\(currentUsername!)&unique=3456364567")
        let request = NSMutableURLRequest(URL: url!)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            if data == nil {
                print("request failed \(error)")
                return
            }

            let parseError: NSError?

            if let json = NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {

                let dropoffIndicator = json["dropoffIndicator"]

                if (dropoffIndicator == "TRUE") {
                    dispatch_async(dispatch_get_main_queue()){
                        let Storyboard = UIStoryboard(name: "Main", bundle: nil)
                        let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("dropoffSuccess") 

                        self.presentViewController(MainVC, animated: true, completion: nil)

                    }
                }

            } else {
                print("parsing error: \(parseError)")
                let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("raw response: \(responseString)")
            }
        }
        task.resume()
    }

问题出在if let json = NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] 行。但是,我很困惑,因为我的代码刚刚使用 Swift 1.2。我真的不知道如何解决这个问题。我应该改变什么?

我已经尝试了其他类似问题的所有其他解决方案,但我无法让它发挥作用。我试着做一个 do-catch 组合,但它只会给我更多的错误。

编辑:我想不通的新代码

@IBAction func editingCodeChanged(sender: AnyObject) {
        checkMaxLength(sender as! UITextField, maxLength: 4)

        let currentUsername = PFUser.currentUser()!.username

        if ((UnlockCodeField.text!).characters.count == 4) {
            let url = NSURL(string: "http://test.informatica-corlaer.nl/unlockCodeTransmitter.php?user=\(currentUsername!)&unique=5782338593203")
            let request = NSMutableURLRequest(URL: url!)

            // modify the request as necessary, if necessary

            let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
                data, response, error in

                if data == nil {
                    print("request failed \(error)")
                    return
                }

                let parseError: NSError?
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {

                    let databaseUnlockCode = json["unlockCode"]

                    let enteredUnlockCode = self.UnlockCodeField.text!

                    if (databaseUnlockCode == enteredUnlockCode) {
                        dispatch_async(dispatch_get_main_queue()){
                            let Storyboard = UIStoryboard(name: "Main", bundle: nil)
                            let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("VehiclePurchaseStatus") 

                            self.presentViewController(MainVC, animated: true, completion: nil)

                            let myUrl = NSURL(string: "http://test.informatica-corlaer.nl/VEPunlockExecuter.php?user=\(currentUsername!)&unique=8648604386910");
                            let request = NSMutableURLRequest(URL:myUrl!);
                            request.HTTPMethod = "POST";

                            NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
                                {
                                    (response, data, error) in
                                    print(response)

                            }

                        }
                    } else {
                        dispatch_async(dispatch_get_main_queue()){

                            let alert = UIAlertView()
                            alert.title = "Whoops!"
                            alert.message = "You entered the wrong code. Please enter the code displayed on the VEP screen."
                            alert.addButtonWithTitle("OK")
                            alert.show()

                        }
                    }

                } else {
                    print("parsing error: \(parseError)")
                    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    print("raw response: \(responseString)")
                }
            }
            task.resume()

        }
    }

【问题讨论】:

标签: json xcode try-catch swift2 throw


【解决方案1】:

尝试替换

if let json = NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {
    let dropoffIndicator = json["dropoffIndicator"]

    if (dropoffIndicator == "TRUE") {
        dispatch_async(dispatch_get_main_queue()){
            let Storyboard = UIStoryboard(name: "Main", bundle: nil)
            let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("dropoffSuccess") 

            self.presentViewController(MainVC, animated: true, completion: nil)

            }
        }
    } else {
        print("parsing error: \(parseError)")
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("raw response: \(responseString)")
    }
}

do {
    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {
        let dropoffIndicator = json["dropoffIndicator"]

        if (dropoffIndicator == "TRUE") {
            dispatch_async(dispatch_get_main_queue()){
                let Storyboard = UIStoryboard(name: "Main", bundle: nil)
                let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("dropoffSuccess") 

                self.presentViewController(MainVC, animated: true, completion: nil)

                }
            }
        } else {
            print("parsing error: \(parseError)")
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("raw response: \(responseString)")
        }
    }
} catch (_) {
    print("...")
}

统一更新: 完整代码:

func recognizeDropoff() {
    let currentUsername = PFUser.currentUser()!.username

    let url = NSURL(string: "http://test.informatica-corlaer.nl/dropoffRecognizer.php?user=\(currentUsername!)&unique=3456364567")
    let request = NSMutableURLRequest(URL: url!)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if data == nil {
            print("request failed \(error)")
            return
        }

        var parseError: NSError?

        do {
            if let json = NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {

                let dropoffIndicator = json["dropoffIndicator"]

                if (dropoffIndicator == "TRUE") {
                    dispatch_async(dispatch_get_main_queue()){
                        let Storyboard = UIStoryboard(name: "Main", bundle: nil)
                        let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("dropoffSuccess") 

                        self.presentViewController(MainVC, animated: true, completion: nil)

                    }
                }

            } else {
                print("parsing error: \(parseError)")
                let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("raw response: \(responseString)")
            }
        } catch {
            print("...")
        }
    }
    task.resume()
}

【讨论】:

  • 我尝试了该解决方案,但它只会在整个函数中返回更多错误,例如'catch() {' 行中的'expected expression' 和'操作符=='的模糊使用线if data == nil{。此外,我收到多个错误type of expression is ambiguous without more context。函数中有很多错误,我完全糊涂了。我该怎么办?我想我还没有为 Swift 2 做好准备,但我真的同时需要它。
  • @JesperProvoost 我在我的答案中添加了完整的代码,试试这个。在 xcode 7.1 上对我有用
  • 非常感谢!这适用于该功能!但是,现在我在另一个函数中遇到了同样的问题。我编辑了我的开篇文章,向您展示了这个功能。我应该如何更改此特定功能以使其正常工作?
  • @JesperProvoost 您需要包装到do { ... } catch { ... } 可能导致异常的部分代码。在if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {之前写do {
【解决方案2】:
let j = try? NSJSONSerialization.JSONObjectWithData(data!, options: [])
if let json = j as? [String: String] {
    // all your original code
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    相关资源
    最近更新 更多