HarryMoy
HarryMoy

Reputation: 171

Issue with Swift 2 Error Handling

I am using REST to get JSON data and then parse it. To do this I am using NSJSONObjectWithData, as far as I'm aware this method used to have an error handler within its parameters but it's no longer there. In my code here:

let err: NSError?
let options:NSJSONReadingOptions = NSJSONReadingOptions.MutableContainers
var jsonResult = NSJSONSerialization.JSONObjectWithData(data!, options: options) as! NSDictionary;

I get an error which says:

"Call can throw, but it is not marked with 'try' and the error is not handled"

How would I go about fixing this error?

Upvotes: 4

Views: 214

Answers (1)

itsji10dra
itsji10dra

Reputation: 4675

Here is the correct implementation,

do {
    let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

    //Use your dictionary here.
    print("JSON : \(jsonDictionary)")
}
catch  {
    print(error)
    //Handle any error.
}

Upvotes: 3

Related Questions