iosswiftswift3avfoundationnscache

Cannot generate Video Thumbnails with Cache in Swift


Been struggling to make it work. I am generating the Video Thumbnails but it's loading really heavily in a collection view. I would like to cache them and I can not find a solution.

This is the code I am using:

func previewImageFromVideo(url:NSURL) -> UIImage? {


    let asset = AVAsset(url: url as URL)
    let imageGenerator = AVAssetImageGenerator(asset:asset)
    imageGenerator.appliesPreferredTrackTransform = true
    imageGenerator.maximumSize = CGSize(width: 250, height: 120)

    var time = asset.duration
    time.value = min(time.value,2)

    do {
        let imageRef = try imageGenerator.copyCGImage(at: time, actualTime: nil)
        return UIImage(cgImage: imageRef)
    } catch {
        return nil
    }
}

I've made them very small, but still connecting every time to the server. Please help.


Solution

  • You can use the URLCache:

    func previewImageFromVideo(url: NSURL) -> UIImage? {
        let url = url as URL
        let request = URLRequest(url: url)
        let cache = URLCache.shared
    
        if
            let cachedResponse = cache.cachedResponse(for: request),
            let image = UIImage(data: cachedResponse.data)
        {
            return image
        }
    
        let asset = AVAsset(url: url)
        let imageGenerator = AVAssetImageGenerator(asset: asset)
        imageGenerator.appliesPreferredTrackTransform = true
        imageGenerator.maximumSize = CGSize(width: 250, height: 120)
    
        var time = asset.duration
        time.value = min(time.value, 2)
    
        var image: UIImage?
    
        do {
            let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
            image = UIImage(cgImage: cgImage)
        } catch { }
    
        if
            let image = image,
            let data = UIImagePNGRepresentation(image),
            let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)
        {
            let cachedResponse = CachedURLResponse(response: response, data: data)
    
            cache.storeCachedResponse(cachedResponse, for: request)
        }
    
        return image
    }