【发布时间】:2015-06-29 19:55:58
【问题描述】:
在我的应用程序中,我正在获取 JSON 数据。有时,应用程序将无法获取它,当我打印 responseObject 时,它会返回 ()。我想做一个 if 语句,这样当这种情况发生时,一个 UIAlertView 就会出现。现在,我有一个 if 语句说如果 self.jobs == nil,警报会出现,但这不起作用。非常感谢任何帮助!
- (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];
}];
【问题讨论】:
-
还要注意http状态码
[operation.response statusCode],你甚至可能得到一个服务器状态码。 -
以后,不要第二次发布您的问题。您应该更新之前的问题以澄清问题,而不是发布此问题。
标签: ios objective-c json uialertview