检索失败后获取JSON数据 [英] Fetching JSON data after failed retrieval
问题描述
在我的应用程序中,我正在获取JSON数据.有时,应用程序将无法获取它,并且当我打印responseObject时,它将返回().我想做一个if语句,以便当发生这种情况时,将显示一个UIAlertView.现在,我有一条if语句,如果self.jobs == nil,警报将会出现,但是那是行不通的.非常感谢您的帮助!
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];
}];
推荐答案
听起来像是在返回一个空响应,所以null检查总是解析为true.尝试检查NSArray
的计数是否大于0而不是if(self.jobs != nil)
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)
只需将if(self.jobs != nil)
更改为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)
这篇关于检索失败后获取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!