-1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Max
  • 1,341
  • 3
  • 20
  • 39
  • The JSONObjectWithData operation will not generate an exception so long as the NSData operand is indeed an NSData. Whether what you get is an NSArray or an NSDictionary (or nil) depends on what is in the JSON string. – Hot Licks Jul 13 '14 at 18:39

2 Answers2

1

(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)
        }
    }
DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • NSJSONSerialization should return type. In my example it is: Array. – Max Jul 13 '14 at 19:00
  • 1
    It returns `AnyObject!` because you cannot know at compile time whether a dictionary or array (or string?) will be returned. You have to check (and cast) at runtime. – DarkDust Jul 13 '14 at 19:06
0

This probably happens because JSONObjectWithData is declared to return id, but in reality it returns NSDictionary*, NSArray* or nil - in Swift, assigning nil to a variable of type id crashes by design. You need to give jsonDict a type, probably an optional NSMutableDictionary* or NSMutableArray*.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • It won't NSMutableDictionary or NSMutableArray in my example. Can you give yours? – Max Jul 13 '14 at 19:01
  • Look at your call. You asked for mutable containers. Therefore it will return a mutable container, not an immutable container. You asked for mutable, you get mutable. Or nil in case of error. – gnasher729 Jul 13 '14 at 19:21