需求是調用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()?
謝謝你的回答幫助我。 – Sandy