ViewController.swift
func thumnailImageForFileUrl(fileUrl: URL) -> UIImage? {
let asset = AVAsset(url: fileUrl)
let imageGenerator = AVAssetImageGenerator(asset: asset)
do {
let thumnailCGImage = try imageGenerator.copyCGImage(at: CMTimeMake(value: 1,timescale: 60), actualTime: nil)
print("サムネイルの切り取り成功!")
return UIImage(cgImage: thumnailCGImage, scale: 0, orientation: .right)
}catch let err{
print("エラー\(err)")
}
return nil
}
AVAsset+.swift
import AVFoundation
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, scale: 0, orientation: .right))
} else {
completion(nil)
}
})
}
}
}
fileUrlに動画のURLを渡すとサムネイルを生成して返してくれます。