Marcus
Marcus

Reputation: 9472

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

Upvotes: 3

Views: 5307

Answers (2)

Rob
Rob

Reputation: 437632

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

Upvotes: 3

TwoStraws
TwoStraws

Reputation: 13127

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.

Upvotes: 2

Related Questions