Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Try/Catch NSJSONSerialization

I'm running a NSJSONSerialization command with try catches but it is still failing when the command returns a nil. What am I doing incorrect with my try catches?

fatal error: unexpectedly found nil while unwrapping an Optional value happens at the line where z is set. Why doesn't the catch handle this?

    func reachForWebsite(){
    let url = NSURL(string: "https://myURL")
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        do {
            let z = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as! [NSObject: AnyObject]
        } catch let myJSONError {
            print(myJSONError)
        }
    }
    task!.resume()
}
like image 311
Marcus Avatar asked Feb 12 '26 14:02

Marcus


2 Answers

The do-try-catch process catches errors that are thrown, but is not a generalized exception handling process. As before, as a developer, you are still responsible for preventing exceptions from arising (e.g. the forced unwrapping of the optional NSData).

So, check to make sure data is not nil before proceeding. Likewise, don't use as! in the cast unless you are assured that the cast cannot fail. It is safer to guard against data being nil and perform an optional binding of the JSON to a dictionary:

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { data, response, error in
    guard data != nil else {
        print(error)
        return
    }

    do {
        if let z = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [String: AnyObject] {
            // do something with z
        }
    } catch let parseError {
        print(parseError)
    }
}
task.resume()
like image 153
Rob Avatar answered Feb 14 '26 04:02

Rob


You need to check the values of error and data before trying to give them to NSJSONSerialization to parse – data is probably nil, which is what triggers your crash.

like image 41
TwoStraws Avatar answered Feb 14 '26 03:02

TwoStraws



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!