PHImageManager crash after many image requests
I am trying to grab all users PHAsset
with PHAssetMediaTypeImage
and then iterate over them, getting the matching UIImages
one at a time. I have about 2k photos on my iPhone 5 and this code crashes after iterating through 587 of them.
PHFetchResult *fr = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
PHImageManager *manager = [PHImageManager defaultManager];
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.synchronous = YES;
__block int i = 0;
for (PHAsset *result in fr)
{
[manager requestImageForAsset:result targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage *image, NSDictionary *info) {
NSLog(@"%d", i);
i++;
}];
}
Exception reading EXC_BAD_ACCESS (code = 1, address = 0x0). Any help pointing me in the right direction would be enormously appreciated.
source to share
Closing the loop on this. The images are not released until the for loop has finished, so you need to add @autoreleasepool to drain the pool after each iteration of the loop, for example
PHFetchResult *fr = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
PHImageManager *manager = [PHImageManager defaultManager];
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.synchronous = YES;
__block int i = 0;
for (PHAsset *result in fr)
{
@autoreleasepool {
[manager requestImageForAsset:result targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage *image, NSDictionary *info) {
NSLog(@"%d", i);
i++;
}];
}
}
source to share
The problem for me was found in this line of code
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info) in cell.setThumbnailImage(result)
})
The targetSize parameter was passed the PHImageManagerMaximumSize value which was the culprit. I changed it to lCgSize
, lCgSize = CGSizeMake(105, 105);
solved the problem.
According to PHImageManagerMaximumSize documentation
When you use the PHImageManagerMaximumSize parameter, photos provide the largest image available for an asset without scaling or cropping. (That is, it ignores the resizeMode parameter.)
So this explains the problem. I believe if it was one image it shouldn't be a problem, but if there were many images the device ran out of memory.
source to share