Question

I am accessing data from the json web services into my application. whenever there is no json data the app gets crashed, I am using nsjsonserialization is there anyway I can find out the empty array at response itself and display the error, thus not making app gets crashed.

Was it helpful?

Solution

try this . . . .

NSArray * dataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

if (dataArray != nil) {

     // perform parsing
}

OTHER TIPS

If you want to check if it is empty:

 if ([myMutableArray count] != 0) { ... }

If you want to check if the variable is nil:

 if (myMutableArray) { ... }

or:

 if (myMutableArray != nil) { ... }

Check if data is nil or if any error occurred or data length

[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
        {
            NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                NSLog(@"responseCode: %d", responseCode);  //check response code

            if ([data length] > 0 && error == nil)

              //data downloaded -> continue
             NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

            else if ([data length] == 0 && error == nil)
                //empty reply
            else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
               // time out
            else if (error != nil)
                //error
        }];

The Exception as expected.. Try the condition whether it has the JSon Value Or Not :

Something like this :

 UserDetails = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:nil];
 NSLog(@"User Det %@", UserDetails);

 if (!UserDetails){ 
     NSLog(@"Doesn't exist");
 }else{ 
     NSlog(@"%@",[UserDetails objectForKey:@"lastName"]);
        .....
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top