cstrap
9/6/2012 - 2:23 AM

Example of working tableview with async images

Example of working tableview with async images

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    
    static NSString *CellIdentifier = @"Cell";
    CGSize newSize = CGSizeMake(70, 70);
    Story *currentStory = [[storyParser stories] objectAtIndex:indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
 
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
	} 
    
    cell.textLabel.textColor = [UIColor whiteColor];
    
    cell.imageView.image = [UIImage imageNamed:@"tableviewDefault"];
    
    
    //Load images from web asynchronously with GCD
    if(!currentStory.image){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        
            if (currentStory.imageURL) {
                
                NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:currentStory.imageURL]];
                dispatch_sync(dispatch_get_main_queue(), ^{ 
                
                    currentStory.image = [UIImage imageWithData:data];
                    UIImage *resizedImage = [self imageWithImage:currentStory.image scaledToSize:newSize];
                    cell.imageView.image = resizedImage;
                    [self.tableView beginUpdates];
                    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil]
                                          withRowAnimation:UITableViewRowAnimationNone];
                    [self.tableView endUpdates];
                });
                
            } else
                cell.imageView.image = [UIImage imageNamed:@"tableviewDefault"];
             
        });
    }
    else {
        UIImage *resizedImage = [self imageWithImage:currentStory.image scaledToSize:newSize];
        cell.imageView.image = resizedImage;
    }
    
    cell.textLabel.text = [self addElipses: currentStory.title];
    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    
    return cell;
}