无法在 Swift 中使用缓存生成视频缩略图

Cannot generate Video Thumbnails with Cache in Swift

一直在努力让它发挥作用。我正在生成视频缩略图,但它在集合视图中的加载量非常大。我想缓存它们,但找不到解决方案。

这是我使用的代码:

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
    }
}

我已经把它们做得很小了,但每次仍然连接到服务器。请帮忙

您可以使用 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
}

我创建此扩展程序是为了创建和缓存来自文件管理器的视频的视频缩略图。

你可以这样使用:

 let videoURL = URL(fileURLWithPath: self.videoPath)
 let thumbnailImage = videoURL.createVideoThumbnail()

扩展代码:

let imageCache = NSCache<AnyObject, AnyObject>()

extension URL {

   func createVideoThumbnail() -> UIImage? {

    if let imageFromCache = imageCache.object(forKey: self as AnyObject) as? UIImage {
        return imageFromCache
    }

    let asset = AVAsset(url: self)
    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 cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
        let image = UIImage(cgImage: cgImage)
        imageCache.setObject(image as AnyObject, forKey: self as AnyObject)
        return image
    } catch let err {
        print(err)
     }
    return UIImage()
  }
}