Created
January 31, 2014 15:45
-
-
Save dokun1/8734572 to your computer and use it in GitHub Desktop.
Asynchronous Image Loading in UICollectionViewCell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { | |
static NSString *cellIdentifier = @"AfterpartyPhotoCell"; | |
AfterpartyPhotoCell *cell = (AfterpartyPhotoCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; | |
if (!cell) | |
cell = [[AfterpartyPhotoCell alloc] init]; | |
[cell.downloadIndicator startAnimating]; | |
cell.downloadIndicator.center = cell.center; | |
cell.imageView.contentMode = UIViewContentModeScaleAspectFill; | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ | |
BOOL shouldDownload = YES; | |
UIImage *image = _thumbnailCacheDict[[NSString stringWithFormat:@"%lld", (long long)indexPath.item]]; | |
if (image != nil) { | |
shouldDownload = NO; | |
CGSize newSize = [self sizePhotoForColumn:image.size]; | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
CGRect frame = cell.imageView.frame; | |
frame.size = newSize; | |
cell.imageView.frame = frame; | |
cell.layer.borderColor = [[UIColor whiteColor] CGColor]; | |
cell.layer.borderWidth = 0.5f; | |
[cell.downloadIndicator stopAnimating]; | |
cell.downloadIndicator.hidden = YES; | |
[cell.imageView setImage:image]; | |
}); | |
} | |
if (shouldDownload) { | |
AfterpartyPhotoInfo *photoInfo = _photoMetadata[indexPath.item]; | |
CGSize newSize = [self sizePhotoForColumn:[photoInfo size]]; | |
[_cm downloadImageForRefID:[photoInfo thumbID] completion:^(NSData *imageData, NSError *error) { | |
if (!error && imageData != nil) { | |
UIImage *image = [[UIImage alloc] initWithData:imageData]; | |
[_thumbnailCacheDict setObject:image forKey:[NSString stringWithFormat:@"%lld", (long long)indexPath.item]]; | |
dispatch_async(dispatch_get_main_queue(), ^{ | |
CGRect frame = cell.imageView.frame; | |
frame.size = newSize; | |
cell.imageView.frame = frame; | |
cell.layer.borderColor = [[UIColor whiteColor] CGColor]; | |
cell.layer.borderWidth = 0.5f; | |
[cell.downloadIndicator stopAnimating]; | |
cell.downloadIndicator.hidden = YES; | |
[cell.imageView setImage:image]; | |
}); | |
} | |
}]; | |
} | |
}); | |
return cell; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment