Search code examples
swiftmemory-leaksuiimagecgimageavasset

Memory Consumption issue in the image generation from Video - AVAsset


I want to create the Photos like video view , where in footer I there will be one one second's frame of video.

enter image description here

for that I am using this code

var imgs : [UIImage] = []
let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: video)
assetImgGenerate.appliesPreferredTrackTransform = true

let duration = Int(CMTimeGetSeconds(video.duration))
    for i in 0 ... duration   {
        if let img = generateFrames(assetImgGenerate : assetImgGenerate , fromTime: Float64(i))
        {
            imgs.append(img)

        }

The code is working fine. I am getting the same result as I want.

Now the issue is - If the video size is more then 50 seconds and I am extracting the uiimage then my app crashes as the memory goes beyond the free space of device.

My videos are of 120 to 200 seconds. What can be better approach for this in terms of memory management. (I can not do lazy loading of the images as I want the images to be preloaded in the screen.)

EDIT

 func generateFrames(assetImgGenerate : AVAssetImageGenerator,   fromTime:Float64) -> UIImage? {

    let time : CMTime = CMTimeMakeWithSeconds(fromTime, 1)
    var img: CGImage?

  img = try? assetImgGenerate.copyCGImage(at:time, actualTime: nil)

}

Solution

  • Try to specify the maximumSize of the thumbnail image. e.g.

    let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: video)
    assetImgGenerate.appliesPreferredTrackTransform = true
    // Here specify the size in which you want to fit the image.
    assetImgGenerate.maximumSize = CGSize(width: 100, height: 100)
    

    It's the array of images that is consuming lot of memory if the image size is large.