2016-06-19 35 views
0

需求是調用edmunds API並在應用啓動後立即在表中顯示供應商名稱。如何在加載tableview之前執行API方法?

1)-getAPIData()

檢索在self.dealerName陣列經銷商和商店的名稱。

-(void)getAPIData{ 
    NSURLSession *session = [NSURLSession sharedSession]; 
    self.task = [session dataTaskWithURL:[NSURL URLWithString:[NSString stringWithFormat: 
               @"https://api.edmunds.com/api/dealer/v2/dealers?zipcode=%@&radius=%@&fmt=json&api_key=ycwedw68qast829zx7sn9jnq", 
               @"01609",@"10"]] 
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
     if (data.length > 0 && error == nil) 
     { 
      NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data 
                    options:kNilOptions 
                    error:NULL]; 
      self.dealersDictionary = jsonData[@"dealers"]; 
      for (id item in self.dealersDictionary){ 
       if (item[@"name"] != nil){ 
        self.dealerName = item[@"name"]; 
        NSLog(@"%@",self.dealerName); 
       }else{ 
        NSLog(@"could'nt find the names"); 
       } 
      } 
     } 
    } 
]; 
} 

2)-viewDidLoad()

此方法調用getAPIData(上述方法)。

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self getAPIData]; 
} 

3) - (NSInteger的)的tableView:(UITableView的*)的tableview numberOfRowsInSection:(NSInteger的)部分

返回經銷商計數。

-(NSInteger)tableView:(UITableView *)tableview numberOfRowsInSection:(NSInteger)section 
{ 
    [self.task resume]; 
    return self.dealerName.count; 
} 

getAPIData()方法在調用numberOfRowsInSection()後執行。所以,表格被渲染爲空。

如何在屏幕上加載表之前調用getAPIData()?

回答

0

我認爲這裏的問題是NSURLSession dataTaskWithURL是異步的。

認爲您可以繼續使用異步方法,並在調用成功返回後(例如,在您的完成處理程序中)調用[self.tableView reloadData];。您可以在等待負載完成時顯示活動指示器。

或者你可以做一個阻塞,同步請求就像這樣:

// define the URL 
NSURL url = [NSURL URLWithString: @"https://api.edmunds.com/api/dealer/v2/dealers?zipcode=%@&radius=%@&fmt=json&api_key=ycwedw68qast829zx7sn9jnq"]; 

// attempt the request 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
                cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData 
                timeoutInterval:10]; 
[request setHTTPMethod: @"GET"]; 

NSError *reqError; 
NSURLResponse *urlResponse; 
NSData *returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&reqError]; 

// parse `returnedData` here 

現在你將有你的NSData對象,你可以在這裏解析它在你completionHandler在做同樣的方式。如果您相信您的請求響應將很快返回,則此選項可行。

最終選項:使用NSURLConnection執行異步請求並使用其- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data委託方法更新UIProgressView以獲取更加精確的活動指示。如果您的請求響應時間足以讓用戶想知道是否發生了任何事情(例如,超過幾秒鐘),我鼓勵您查看此方法。

+0

謝謝你的回答幫助我。 – Sandy

8

簡答:你沒有。您顯示一個空的表視圖,然後在完成塊中,調用tableView的reloadData方法,然後加載其內容。

+2

您也可以將響應存儲在緩存中,以便下次啓動應用程序時,您可以在等待新數據時立即顯示數據。由於您無論如何都對郵政編碼進行了硬編碼,因此這將非常容易。 –

+0

@DanielT。,這是真的,也許是一個好主意。 –

相關問題