I understand that there are many of these issues, but none of them seem to address this case.
CollectionView reads the file names from the files array and loads images from the Documents directory or loads them, displays and saves them to Documents. It works perfectly smoothly and without any additional libraries, HOWEVER, when scrolling through several cells quickly, they get the wrong image. Calling [collectionView reloadData] with any action or scrolling reloads these incorrect images into good ones.
I assume this is due to the reuse of cells with an asynchronous image assignment, but how to solve this problem? CollectionView and custom cell defined in Storyboard. Images are stored on the server for basic authentication, so most reuse solutions are not applied.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { BrowseCollectionViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath]; NSString *fileName = [files objectAtIndex:indexPath.item]; NSString *filePath = [thumbDir stringByAppendingPathComponent:fileName]; if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { cell.imageView.image = [UIImage imageWithContentsOfFile:filePath]; } else //DOWNLOAD { NSString *strURL = [NSString stringWithFormat:@"%@%@", THUMBURL, fileName]; NSURL *fileURL = [NSURL URLWithString:strURL]; cell.imageView.image = [UIImage imageNamed:@"placeholder.jpg"]; [self downloadFromURL:fileURL to:filePath completionBlock:^(BOOL succeeded, UIImage *image) { if (succeeded) { cell.imageView.image = image; } }]; } } cell.imageName = fileName; return cell; } - (void)downloadFromURL:(NSURL*)url to:(NSString *)filePath completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock { NSString *authStr = [NSString stringWithFormat:@"%@:%@", LOGIN, PASS]; NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding]; NSString *authValue = [authData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:30]; [request setValue:[NSString stringWithFormat:@"Basic %@", authValue] forHTTPHeaderField:@"Authorization"]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (!error) { UIImage *image = [[UIImage alloc] initWithData:data]; [data writeToFile:filePath atomically:NO]; completionBlock(YES, image); } else { completionBlock(NO, nil); } }]; }
I tried a lot of changes, but none of them seemed to solve the problem. Currently, the effect is that new cells that appear during fast scrolling change more than once, and some of them always end up with the wrong image, indicating some reuse problem.
Thanks in advance for any help or suggestions.
source share