Search code examples
iosuitableviewphotokit

Getting fixed size Image from PHCachingImageManager


I'm trying to get thumbnails from my PHCachingImageManager so that I can put them into the built-in imageView in my UITableViewCells.

NSLog(@"thumbnail size: %@", NSStringFromCGSize(AssetGridThumbnailSize));
[self.imageManager
    requestImageForAsset:asset
        targetSize:AssetGridThumbnailSize
       contentMode:PHImageContentModeAspectFill
           options:nil
     resultHandler:^(UIImage *result, NSDictionary *info) {

       NSLog(@"image size: %@", NSStringFromCGSize(result.size));

       // Only update the thumbnail if the cell tag hasn't changed. Otherwise, the cell has been re-used.
       if (cell.tag == currentTag) {
           cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
           cell.imageView.image = result;

       }
}];

I can see that AssetGridThumbnailSize = 80 x 80 (40 x 40 retina) from the logs:

thumbnail size: {80, 80}

and I've set the contentMode to PHImageContentModeAspectFill but when I get the images back they are all different sizes and it makes the UITableView look very chaotic.

How can I make the PHCachingImageManager give me back an image of the right size?


Solution

  • While posting the question, I figured out the answer so I decided to continue posting and hopefully this will help someone else.

    The targetSize is just a suggestion. In order to really control the size of the returned images you have to pass in a PHImageRequestOptions object with resizeMode = PHImageRequestOptionsResizeModeExact.

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    
    [self.imageManager requestImageForAsset:asset
                     targetSize:AssetGridThumbnailSize
                    contentMode:PHImageContentModeAspectFill
                        options:options
                  resultHandler:^(UIImage *result, NSDictionary *info) {