2015-06-29 78 views
0

在我的應用程序中,我正在獲取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]; 
    }]; 
+0

另外要注意的HTTP狀態代碼'[operation.response的StatusCode ]',你甚至可能會得到一個服務器狀態碼。 – zaph

+1

未來,不要再次發佈您的問題。不要發佈這個問題,你應該更新你以前的問題來澄清事情。 – rmaddy

回答

2

聽起來像你正在收回一個空的響應,所以空檢查總是解決爲真。嘗試檢查NSArray的計數是否大於0而不是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]; 
} 

您可能還需要你嘗試並進行計數,以避免任何空引用異常之前做一個空檢查:

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

更新了答案 – pnavk