要求是在应用启动后立即调用 edmunds 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)section
返回经销商数量。
-(NSInteger)tableView:(UITableView *)tableview numberOfRowsInSection:(NSInteger)section
{
[self.task resume];
return self.dealerName.count;
}
getAPIData() 方法在调用 numberOfRowsInSection() 之后执行。因此,表格呈现为空。
如何在表格加载到屏幕之前调用 getAPIData()?
最佳答案
简短的回答:你不知道。您显示一个空 TableView ,然后在完成 block 中调用 tableView 的 reloadData 方法,然后加载其内容。
关于ios - 如何在加载tableview之前执行API方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37912482/