Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle NSJSONSerialization's crashing when disconnected to internet

I implement web service in my app. My way is typical.

- (BOOL)application:(UIApplication *)application     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Web Service  xxx,yyy are not true data
    NSString *urlString =   @"http://xxx.byethost17.com/yyy";
    NSURL *url = [NSURL URLWithString:urlString];
    dispatch_async(kBackGroudQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: url];
        [self performSelectorOnMainThread:@selector(receiveLatest:)     withObject:data waitUntilDone:YES];
    });   
    return YES;
}

- (void)receiveLatest:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData
                      options:kNilOptions
                      error:&error];
    NSString *Draw_539 = [json objectForKey:@"Draw_539"];
....

console error message:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

When my iphone has connection to Internet, the app works successfully. But if it disconnects to Internet, app will crash on NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; Can you show me how to handle this error? Is NSError helpful?

like image 405
bc a Avatar asked Nov 29 '22 12:11

bc a


1 Answers

The error is telling you that "responseData" is nil. The way to avoid the exception is to test "responseData" and not invoke JSONObjectWithData if it's nil. Instead react however you feel you should for this error condition.

like image 186
Hot Licks Avatar answered Dec 16 '22 03:12

Hot Licks