首页 文章

Swift 2 JSON调用可以抛出,但它没有标记'try'并且未处理错误

提问于
浏览
1

我有一个名为recognDropoff的函数,它在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组合,但它只给了我更多的错误 .

EDIT: New Code that I can't figure out

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

        }
    }

2 回答

  • 0

    尝试更换

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

    UPD: 完整代码:

    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()
    }
    
  • 0
    let j = try? NSJSONSerialization.JSONObjectWithData(data!, options: [])
    if let json = j as? [String: String] {
        // all your original code
    }
    

相关问题