Using Swift 5, as an extension function on AVAsset:
import AVKit
extension AVAsset {
func generateThumbnail(completion: @escaping (UIImage?) -> Void) {
DispatchQueue.global().async {
let imageGenerator = AVAssetImageGenerator(asset: self)
let time = CMTime(seconds: 0.0, preferredTimescale: 600)
let times = [NSValue(time: time)]
imageGenerator.generateCGImagesAsynchronously(forTimes: times, completionHandler: { _, image, _, _, _ in
if let image = image {
completion(UIImage(cgImage: image))
} else {
completion(nil)
}
})
}
}
}
Usage:
AVAsset(url: url).generateThumbnail { [weak self] (image) in
DispatchQueue.main.async {
guard let image = image else { return }
self?.imageView.image = image
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…