1

I have a function called recognizeDropoff and it worked fine with Swift 1.2 in Xcode 6.4. However, now I'm using Xcode 7.1 with Swift 2 and I am getting this error: 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()
    }

The problem is in the line if let json = NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String]. However, I am quite confused because I just got my code working with Swift 1.2. I really can't figure out how to fix this. What should I change?

I have tried all the other solutions from other similar questions, but I just can't get it to work. I tried to make a do-catch combination, but it only gave me more errors.

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

        }
    }
  • Possible duplicate of [How to parse JSON in Swift 2.0 using NSURLSession](http://stackoverflow.com/questions/31805045/how-to-parse-json-in-swift-2-0-using-nsurlsession) – Eric Aya Oct 24 '15 at 18:38

2 Answers2

0

Try replace

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

to

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: Full code:

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()
}
Alexander
  • 2,257
  • 1
  • 18
  • 19
  • I tried that solution, but it only returns more errors in the whole function, for example 'expected expression' at the line 'catch() {' and 'ambiguous use of operator ==' at the line `if data == nil{`. Also, I get multiple errors `type of expression is ambiguous without more context`. There are a lot of errors in the function and I'm totally confused. What should I do about it? I think I wasn't ready for Swift 2 but I really need it at the same time. – Jesper Provoost Oct 25 '15 at 09:13
  • @JesperProvoost i adding full code to my answer, try this. It's work for me on xcode 7.1 – Alexander Oct 25 '15 at 10:29
  • Thank you so much! This works for that function! However, now I'm struggling with the same problem in another function. I edited my opening post to show you this function. How should I change this particular function to make it work? – Jesper Provoost Oct 25 '15 at 11:16
  • @JesperProvoost you need wrap to `do { ... } catch { ... }` part of code which may cause an exception. Write `do {` before `if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: String] {` – Alexander Oct 25 '15 at 11:46
0
let j = try? NSJSONSerialization.JSONObjectWithData(data!, options: [])
if let json = j as? [String: String] {
    // all your original code
}
user3441734
  • 16,722
  • 2
  • 40
  • 59