Generating video thumbnails of all videos from gallery gives memory issues

1.6k views Asked by At

I am working on an application where I need to show the thumbnails of all the videos in my gallery(viewed as collection view).Now I am using AVAssetImageGenerator to generate the thumbnails from videos in gallery but I am getting memory issues.Here is my code that I am using:

    PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:nil];

    PHImageManager *imageManager = [PHImageManager new];

    for(NSInteger i=0 ; i < fetchResult.count ; i++){

     __weak SAVideosViewController *weakSelf = self;
        [imageManager requestAVAssetForVideo:fetchResult[i] options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {

            [collectionViewData addObject:asset];
//my method to generate video thumbnail...
            [self generateThumbnailForAsset:asset];

            if(i == fetchResult.count-1){

                collectionViewDataFilled = YES;

                 dispatch_async(dispatch_get_main_queue(), ^{

                    [weakSelf.myCollectionView reloadData];
                });

            }
        }];
    }

Here is the method called above:

    -(void)generateThumbnailForAsset:(AVAsset*)asset_{

AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset_];
    CMTime time = CMTimeMakeWithSeconds(1,1);
    CMTimeShow(time);
    CGImageRef img = [imageGenerator copyCGImageAtTime:time  actualTime:NULL error:NULL];

if(img != nil){
    NSLog(@"image");
    [thumbnails addObject:[UIImage imageWithCGImage:img]];
}

CGImageRelease(img);

}

I want to know why I'm getting memory issues here and how can I resolve it.

1

There are 1 answers

0
Reckoner On BEST ANSWER

Seems like no one knows the correct answer . So here I am answering my own question after some research .

NOTE : To do such a thing,you do not need to use AVAssetImageGenerator.You the following methods instead(PHOTOS FRAMEWORK).

PHCachingImageManager *cachingImageManager;

[cachingImageManager startCachingImagesForAssets:collectionViewData targetSize:cellSize contentMode:PHImageContentModeAspectFill options:nil];

The class used here is PHCachingImageManager.Read about this in apple docs.

Then after this,use this second method to retrieve data from cache.

    [cachingImageManager requestImageForAsset:collectionViewData[indexPath.row] targetSize:AssetGridThumbnailSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {

        cell.myImageView.image = result;
    }];

The callback handler gives an image that you can use in your collection View cells.use this in cellForItemAtIndexPath method.

For a complete code and reference,refer to this example by APPLE. https://developer.apple.com/library/ios/samplecode/UsingPhotosFramework/Introduction/Intro.html