问题
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