Reputation: 52
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.
Upvotes: -1
Views: 682
Reputation: 15335
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"]);
.....
}
Upvotes: 0
Reputation: 12023
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
}];
Upvotes: 0
Reputation: 3928
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) { ... }
Upvotes: 1
Reputation: 11462
try this . . . .
NSArray * dataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (dataArray != nil) {
// perform parsing
}
Upvotes: 1