Search code examples
iosuiimageviewuiimagephotokit

Cannot get a clear image requested from Photo Album using PhotoKit


I am using PhotoKit to fetch the photos in one of the system albums like this:

PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
[fetchResult enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
    NSLog(@"ALBUM NAME: %@", collection.localizedTitle);
    if ([collection.localizedTitle isEqualToString:@"Camera Roll"]) {
        PHFetchResult *photos = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
        NSLog(@"PHOTOS: %ld", photos.count);
        _photos = nil;
        _photos = @[].mutableCopy;
        for (PHAsset *asset in photos) {
            [self loadImageFromPHAsset:asset];
        }
    }
}];

Then in my custom helper method: (void)loadImageFromPHAsset:(PHAsset *)asset, I have this:

-(void)loadImageFromPHAsset:(PHAsset *)asset
{
    PHImageManager *manager = [PHImageManager defaultManager];
    CGSize targetSize = _layout.itemSize;
    [manager requestImageForAsset:asset targetSize:targetSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage *result, NSDictionary *info) {
        [_photos addObject:result];
    }];
    [self.collectionView reloadData];
}

So I have an array of images and I present them in my UICollectionViewCell:

UIImage *image = [_photos objectAtIndex:indexPath.row];
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
cell.imageView.image = image;

But what I got is like this, it is very blur, how can I make it clear? enter image description here


Solution

  • First of all the targetSize should be multiplied by scale to account for the screen's scale like this,

    CGFloat scale = [UIScreen mainScreen].scale;
    CGSize targetSize = CGSizeMake(_layout.itemSize.width*scale, _layout.itemSize.height*scale);
    

    Secondly, try these options to get the exact size image,

    //Async call returned on main thread, can return multiple times
            
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    

    Lastly, if you have performance concerns, use PHCachingManager, I have answered the question regarding performance improvements here

    Hope this helps you.

    Edit:

    I did not realise that the images were stored in an array. Try setting the synchronous flag in image options.

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.synchronous = YES;
    options.resizeMode = PHImageRequestOptionsResizeModeExact;