0

I am trying to populate the TableViewCells in my TableViewContoller with an Array of data that is being pulled from a JSON object. NSJSONSerialization is simply not getting called.

I've tried a variety of things using DataTaskWithURL. Sadly I'm coming up empty with 0 items found in the array. Thanks in advance for anyone's help!

@property NSArray *toothpastes;

@end

@implementation ToothpastChoicesTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *urlString = @"https://s3.amazonaws.com/mmios8week/toothpastes.json";
    NSURLSession *session = [NSURLSession sharedSession];

    [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^
     (NSData *data,
      NSURLResponse *response,
      NSError *error) {

      if (error) {
         NSLog(@"%@", error);
     } else {

    self.toothpastes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    [self.tableView reloadData]; }

    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSLog(@"%lu", (unsigned long)self.toothpastes.count);

    return self.toothpastes.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID" forIndexPath:indexPath];

    cell.textLabel.text = self.toothpastes[indexPath.row];

    return cell;
}
  • print out the error. – vadian Nov 02 '15 at 17:57
  • hi @vadian - i've tried logging the error but nothing is displaying. I've update the code to include it. Thoughts? Thanks for taking a look. – Patrick Cary Nov 02 '15 at 18:30
  • Is the completion block called at all? Log `self.toothpastes` – and you should reload the table view on the main thread. – vadian Nov 02 '15 at 18:34
  • thanks @vadian. Nothing inside completionHandler^ is getting called as you pointed out. I've moved the reload to the main thread but same result. Is it possible that I should be using a different dataTaskWithURL? – Patrick Cary Nov 02 '15 at 18:48
  • Got it. See my answer. – vadian Nov 02 '15 at 19:12

1 Answers1

0

You forgot to resume the task

NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if (error) {
      NSLog(@"%@", error);
    } else {

     self.toothpastes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
     [self.tableView reloadData]; 
    }
  }];
[task resume];
vadian
  • 274,689
  • 30
  • 353
  • 361