How To Download Images Asynchronously for UITableView

  • CACHE
  • GCD
  • PLACEHOLDER
  • reloadRowsAtIndexPaths
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *cellIdentifier = @"TableCellReuseIdentifier";
  AWTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  if(!cell)
  {
    NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"AWTableCell" owner:self options:nil];
    cell = [nibs objectAtIndex:0];
  }
  AWCourse *node = [self.childrenNodes objectAtIndex:indexPath.row];
  // load image from cache
  if(node.thumbnail) {
    cell.imageView.image = node.thumbnail;
  }
  else {
    // add an image placeholder
    cell.imageView.image = [UIImage imageNamed:@"image_loading.png"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
      // download and resize image
      UIImage *image = [self resizeImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:(node.type==1 ? node.picAudioUrl : node.picUrl)]]] imag$
      if(!cell.imageView) return;
      if(!tableView) return;
      dispatch_async(dispatch_get_main_queue(), ^{
        // cache image
        node.thumbnail = image;
        // Reloads the specified rows using a certain animation effect(fade or none).
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
      });
    });
  }

  return cell;
}