Search code examples
iosobjective-cnsjsonserialization

NSMutable dictionary is nil NSJSONSeralization


I have this code:

NSMutableDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error: &error];

and when the internet connection goes (I am using airplane mode).

I get an error saying responseObject is nil.

I have put this code in straight after it:

if (responseObject == nil){
    dispatch_async(dispatch_get_main_queue(), ^{
        [self ProvidePopUpForNetworkLoss];
    });
}

I am getting the error:

**Terminiating this app due to uncaught exception 'NSInvalidArgumentException' reason 'data parameter is nil' can anyone help ?


Solution

  • When you have no internet connection (or for many other reasons) "data" (wherever you got it from) will be nil. JSONObjectWithData correctly says that it is a programming error to call this method with nil data and throws this exception. Solution: Don't call JSONObjectWithData if the data isn't nil. Anyway, this error should be treated very differently from JSONObjectWithData returning nil. If JSONObjectWithData returns nil, it means there was something wrong with the data you received.

    To find where your problem is, create an exception breakpoint in Xcode. It will stop when the exception is thrown, and that would show you which method threw the exception - it's before your nil check.