How to deal with NSJSONSerialization failure when disconnected from the Internet

I am implementing a web service in my application. My path 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:

* Application termination due to the uncaught exception "NSInvalidArgumentException", reason: "data parameter is zero"

When my iphone has an internet connection, the application runs successfully. But if it disconnects from the Internet, the application crashes on NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; Can you show me how to handle this error? Is NSError ?

+4
source share
2 answers

The error tells you that "responseData" is zero. A way to avoid an exception is to check "responseData" and not call JSONObjectWithData if it is zero. Instead, respond, but you feel that you need this error condition.

+11
source

You do not check if your responseData zero or not before passing it to the JSONObjectWithData:options:error: method.

You should probably try the following:

 - (void)receiveLatest:(NSData *)responseData { //parse out the json data NSError* error; if(responseData != nil) { NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; NSString *Draw_539 = [json objectForKey:@"Draw_539"]; } else { //Handle error or alert user here } .... } 

EDIT-1: For good practice, you should check this error object after the JSONObjectWithData:options:error: method to check and verify whether the JSON data was successfully converted to NSDictionary or not.

 - (void)receiveLatest:(NSData *)responseData { //parse out the json data NSError* error; if(responseData != nil) { NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; if(!error) { NSString *Draw_539 = [json objectForKey:@"Draw_539"]; } else { NSLog(@"Error: %@", [error localizedDescription]); //Do additional data manipulation or handling work here. } } else { //Handle error or alert user here } .... } 

Hope this solves your problem.

Let me know if you need more help.

+9
source

Source: https://habr.com/ru/post/1495433/


All Articles