在我的應用程序中,我正在獲取JSON數據。偶爾,應用程序將無法獲取它,當我打印responseObject時,它將返回()。我想做一個if語句,以便在發生這種情況時,會顯示一個UIAlertView。現在,我有一個if語句說,如果self.jobs ==零,警報會出現,但那是行不通的。我非常感謝任何幫助!檢索失敗後獲取JSON數據
- (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 ]',你甚至可能會得到一個服務器狀態碼。 – zaph
未來,不要再次發佈您的問題。不要發佈這個問題,你應該更新你以前的問題來澄清事情。 – rmaddy