2014-09-25 53 views
0

我正在學習如何解析JSON並將其加載到tableview中,同時我的網絡正在工作數據被正確解析並加載到表格中,但是當我關閉Internet時並刷新我的表格視圖我的用戶界面卡住與以前的JSON數據在同一屏幕上,並在一段時間後崩潰 以下是我如何實現它.. 在我的表視圖控制器我定義此方法正在調用刷新按鈕單擊。下載JSon數據時點擊刷新按鈕時iOS UI被阻塞

- (IBAction) reloadJasonData:(id)sender 
{ 
    NSMutableArray * jsonArray= [DownloadJsonData getJsonArray]; 

    if(! jsonArray) 
    { 
     UIAlertView * errorAlert = [[UIAlertView alloc]initWithTitle:@"Error!!" message:@" Please Check the Internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 

    [errorAlert show]; 

} 
else 
{ 
    NSSortDescriptor * sortDescripter = [[NSSortDescriptor alloc]initWithKey:@"location" ascending:YES]; 
    NSArray * discriptorArray = @[sortDescripter]; 
    self.sortedJsonArray = [jsonArray sortedArrayUsingDescriptors:discriptorArray]; 

    self.arrayOfLinks = [self.sortedJsonArray valueForKey:@"link"]; 
    self.arrayOfLocations = [self.sortedJsonArray valueForKey:@"location"]; 

    self.arrayOfDates = [self.sortedJsonArray valueForKey:@"date_time"]; 
    NSLog(@"Count of cities in fetch data: %d",[self.sortedJsonArray count]); 
    [self.tableView reloadData]; 
} 

}

其他類

我有定義類的方法來下載JSON數據

+(NSMutableArray *) getJsonArray 
{ 
    NSError * error; 
    NSData * data = [NSData dataWithContentsOfURL:httpURL]; 
    NSMutableArray * json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

    return json; 
} 

錯誤消息顯示,只有當我的互聯網連接是不活動的,我點擊刷新按鈕,但一旦數據顯示到表中,我喊我的互聯網,再次點擊刷新按鈕我的用戶界面卡住了..

我希望我已經解釋了我的問題在w所以任何機構都可以幫助我弄清楚它在哪裏搞砸了。提前致謝。

+0

您是否嘗試過我在下面發佈的代碼? – iHulk 2014-09-25 11:10:15

+0

我仍然在努力......我剛開始學習iOS和目標C,所以我需要一點時間來理解事情..我還沒有完全理解代表..所以我還得花一些時間。但感謝您指導我.. – vaibhav 2014-09-25 11:17:27

回答

0

我認爲你使用主線程從互聯網上訪問你的數據,這就是爲什麼你的UI卡住了。您應該使用輔助線程訪問任何遠程數據。

寫代碼的getJsonArray類

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:httpURL]; 
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
    { 
     if (!error && data!=nil) 
      //call a delegate to send the data to your page from where it was called 
     else 
      //show alert that an error has occurred during downloading data from net. 
    }]; 

內,然後使用代表告訴主頁,該數據已經在委託方法下載,然後有重新加載您的tableView在主線程。