New Xcoder
New Xcoder

Reputation: 545

Image Loading Animation issue using GCD

Hi I'm using GCD to load image in the uitableview . Now, the problem is image animation. I called three images from server it loads into the cell but i got 3 problems

1) Single image is repeated in all three cells

2) first and last cell images blinking and changing

3) when the image changed, it is repeated in all cells.

Even though i gave animation none still it animates i.e. Blinking

Code:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...

[imageArray retain];

//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
 //this will start the image loading in bg
 dispatch_async(concurrentQueue, ^{ 
     NSData *image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[imageArray objectAtIndex:indexPath.row]]];

     //this will set the image when loading is finished
     dispatch_async(dispatch_get_main_queue(), ^{
        cell.imageView.image = [UIImage imageWithData:image];

         [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
         });
    });

return cell;

}

Upvotes: 0

Views: 315

Answers (1)

Piotr Tobolski
Piotr Tobolski

Reputation: 1406

You should not download images in this place.

If You don't have too many rows, do this in eg. viewDidLoad and save downloaded images to new mutable array.

Something like this:

- (void) viewDidLoad {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
        int row = 0;
        self.thumbnails = [NSMutableArray array];
        for (NSString *imageURLString in imageArray) {
        //Your way of download images
        NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURLString]];
        UIImage *image = [UIImage imageWithData:imageData];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.thumbnails addObject:image];
            NSArray *indexes = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:1]];
            [self.tableViewOutlet reloadRowsAtIndexPaths:indexes withRowAnimation:UITableViewRowAnimationNone];
        });
        row++;
    }
});
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        if (self.thumbnails && [self.thumbnails count] > indexPath.row) {
            cell.attachmentImageView.image = [self.thumbnails objectAtIndex:indexPath.row];
        } else {
            cell.attachmentImageView.image = nil;
        }
}

Upvotes: 1

Related Questions