Fetching JSON data after failed retrieval

安稳与你 提交于 2019-12-04 06:58:58

问题


In my application, I am fetching JSON data. Occasionally, the application will fail to fetch it and when I print the responseObject, it returns ( ). I would like to make an if statement so that when this happens, a UIAlertView will show up. Right now, I have an if statement saying that if self.jobs == nil, the alert will come up, but that is not working. I'd really appreciate any help!

- (void)viewDidLoad
{

    [super viewDidLoad];

    //Fetch JSON
    NSString *urlAsString = [NSString stringWithFormat:@"https://jobs.github.com/positions.json?description=%@&location=%@", LANGUAGE, TOWN];
    NSURL *url = [NSURL URLWithString:urlAsString];
    NSURLRequest *request = [NSURLRequest requestWithURL: url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    //Parse JSON
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        self.jobs  = (NSArray *)responseObject;

        if(self.jobs != nil)
        {
            [self.tableView reloadData];
        }
        else
        {
            UIAlertView* alert_view = [[UIAlertView alloc]
                                       initWithTitle: @"Failed to retrieve data" message: nil delegate: self
                                       cancelButtonTitle: @"cancel" otherButtonTitles: @"Retry", nil];
            [alert_view show];
        }
    }

     //Upon failure
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        UIAlertView *aV = [[UIAlertView alloc]
                           initWithTitle:@"Error" message:[error localizedDescription] delegate: nil
                           cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [aV show];
    }];

回答1:


Sounds like you are getting back an empty response, so that null check always resolves to true. Try checking if the count of the NSArray is greater than 0 instead of if(self.jobs != nil)

Just change if(self.jobs != nil) to if([self.jobs count] > 0).

if([self.jobs count] > 0)
{
    [self.tableView reloadData];
}
else
{
    UIAlertView* alert_view = [[UIAlertView alloc]
                               initWithTitle: @"Failed to retrieve data" message: nil delegate: self
                               cancelButtonTitle: @"cancel" otherButtonTitles: @"Retry", nil];
    [alert_view show];
}

You might also want to do a null check before you try and do the count to avoid any null reference exceptions:

if(self.jobs != nil && [self.jobs count] > 0)


来源:https://stackoverflow.com/questions/31124439/fetching-json-data-after-failed-retrieval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!