Question

Trying to understand how/why NSError works in this case. I'm trying to do a simple UIAlertview when the JSON query returns no data (either the server is sending it or the user is not on internet). I have looked at about a dozen different answers and am just confusing myself more and more.

- (void)viewDidLoad
{
    [super viewDidLoad];

    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL:
                        kLatestChartDataURL];

        [self performSelectorOnMainThread:@selector(fetchedData:)
                               withObject:data waitUntilDone:YES];


    });
}

- (void)fetchedData:(NSData *)responseData  {


    NSError *error = nil;

    NSArray *theArray = [NSJSONSerialization
                          JSONObjectWithData:responseData
                          options:kNilOptions
                          error:&error];

    NSDictionary *dict0 = [theArray objectAtIndex:147];

    if (NO) {

        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Error"
                                                     message:@"Data failed to load."
                                                     delegate:self
                                                     cancelButtonTitle:@"Ok"
                                                    otherButtonTitles:@"Retry",nil];
        [message show];
    }

I've also tried:

if (!theArray) { 

and

BOOL results = [NSArray etc...

Any thoughts on this would be appreciated, I've also looked at the developer docs and Cocoa is Mygirlfriend examples, and my brain has turned to mush at this point.

Was it helpful?

Solution

Try this

NSError *error = nil;

NSArray *theArray = [NSJSONSerialization
                      JSONObjectWithData:responseData
                      options:kNilOptions
                      error:&error];

if (!theArray) { // DO THIS CHECK
    NSLog(@"error: %@", error);
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Error"
                                                 message:@"Data failed to load."
                                                 delegate:self
                                                 cancelButtonTitle:@"Ok"
                                                otherButtonTitles:@"Retry",nil];
    [message show];
}
else 
{
    NSLog(@"parsed data");
    NSDictionary *dict0 = [theArray objectAtIndex:147];
}

If any error occurs while getting json from NSData then it will be recorded in object of NSError. So if this object is nil means there is no error while parsing json, and if that object holds value means there is some issue while parsing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top