0

I am using array of url's for images to load in collection view. Images are changing while scrolling the collection view. How to fix this issue?

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"RecentProductCell";
    RecentProductCell *recentCell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

            recentCell.recentProductImg.image = nil;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                NSString *imageurl = [[latestProducts valueForKey:@"image"]objectAtIndex:indexPath.item];
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageurl]];

                dispatch_sync(dispatch_get_main_queue(), ^{
                    recentCell.recentProductImg.image = [UIImage imageWithData:imageData];
                });
            });

    }
  • 1
    You are reusing your cells and there is a fetching process happening asynchronously. Store your data in a collection after you fetch them and try to reach them with your indexpath.row to get the exact data every time you reuse your cells. – erenkabakci Oct 16 '15 at 13:35

2 Answers2

0

Replace dispatch_sync(dispatch_get_main_queue(), ^{ recentCell.recentProductImg.image = [UIImage imageWithData:imageData]; });

with

dispatch_sync(dispatch_get_main_queue(), ^{
                if ( imageData )
                {
                  UIImage *urlImage = [[UIImage alloc] initWithData:imageData];
                  RecentProductCell *recentCell = (id)[collectionView cellForItemAtIndexPath:indexPath];
                  if (recentCell)
                       [recentCell.recentProductImg setImage:urlImage];
                }
            });

Let me know if this works for you.

0
cell.imageView.image = nil;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^(void) {

        NSString *imageurl = [[latestProducts valueForKey:@"image"]objectAtIndex:indexPath.item];
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageurl]];

        UIImage* image = [[UIImage alloc] initWithData:imageData];
        if (image) {
             dispatch_async(dispatch_get_main_queue(), ^{
                 if (cell.tag == indexPath.row) {
                     cell.imageView.image = image;
                     [cell setNeedsLayout];
                 }
             });
         }
    });

Write this code in cellForRowAtIndexPath method of collectionView

Vatsal Raval
  • 311
  • 1
  • 9