ios - 如何在加载tableview之前执行API方法?

标签 ios objective-c

要求是在应用启动后立即调用 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/

相关文章:

ios - 如何在不更新应用程序的情况下更新 iPhone 应用程序中的新闻提要?

ios - 带有底部边框的自定义 UITextView

ios - 在后台调用 beginReceivingRemoteControlEvents

ios - 用于从 coredata 查询字符串的子字符串的谓词

ios - 如何为循环添加延迟?

iphone - 选择图像的一部分(剪裁)

ios - Xcode iOS 通用应用程序图像大小

ios - 监控指定时间内UITextField文本变化

ios - sqlite3_open() 中的参数

objective-c - 在 C 中对复数执行矩阵运算