vendredi 24 juin 2016

How to execute the API method before tableview is loaded?

The requirement is to call edmunds API and display the vendors name in a table as soon as the app launches.

1) -getAPIData()

Retrieves the names of dealers and stores in self.dealerName array.

-(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()

This method calls getAPIData(above method).

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

3) -(NSInteger)tableView:(UITableView *)tableview numberOfRowsInSection:(NSInteger)section

Returns the dealers count.

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

getAPIData() method is executing after the numberOfRowsInSection() is called. So, the table is rendered empty.

How do I call the getAPIData() before table is loaded on screen?

Aucun commentaire:

Enregistrer un commentaire