Search code examples
iosjsonswiftexc-bad-instruction

NSJSONSerialization no returns error


There code:

var err: NSError
var jsonDict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as Array<NSDictionary>

If data has JSON it's works perfect. But if there something other (not JSON Array) it's just has fatal error and iOS simulator close with EXC_BAD_INSTRUCTION. So there no call err. How I can check data before? Or catch the error.


Solution

  • (Sorry, am in a hurry, no description yet.)

        var err: NSError?
        var jsonDict: AnyObject!
        var data: AnyObject = "{ }".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        if let d = data as? NSData {
            jsonDict = NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions.MutableContainers, error: &err)
            if let dict = jsonDict as? NSDictionary {
                // Do something with `dict`
                println(dict)
            }
        }