문제

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.

도움이 되었습니까?

해결책

try this . . . .

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

if (dataArray != nil) {

     // perform parsing
}

다른 팁

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"]);
        .....
 }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top