gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:04:20 25 4
gpt4 key购买 nike

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

这是我使用的代码:

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
}

关于ios - 无法在 Swift 中使用缓存生成视频缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52156897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com