我正在使用以下UIImages
视频创建generateCGImagesAsynchronouslyForTimes
:
fileprivate func createImageFramesFromVideo(completion: @escaping ([UIImage]) -> Void) {
guard let url = self.videoUrl else {
return
}
let asset = AVAsset(url: url)
let imageGenerator = AVAssetImageGenerator(asset: asset)
let videoDuration = asset.duration
//getting image snapshots more or less in half the video
let time1 = CMTime(value: videoDuration.value/2 - videoDuration.value/10, timescale: videoDuration.timescale)
let time2 = CMTime(value: videoDuration.value/2 - videoDuration.value/11, timescale: videoDuration.timescale)
let time3 = CMTime(value: videoDuration.value/2 - videoDuration.value/12, timescale: videoDuration.timescale)
let time4 = CMTime(value: videoDuration.value/2, timescale: videoDuration.timescale)
let time5 = CMTime(value: videoDuration.value/2 + videoDuration.value/12, timescale: videoDuration.timescale)
let time6 = CMTime(value: videoDuration.value/2 + videoDuration.value/11, timescale: videoDuration.timescale)
let time7 = CMTime(value: videoDuration.value/2 + videoDuration.value/10, timescale: videoDuration.timescale)
var imageArray : [UIImage] = []
imageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time1), NSValue(time: time2), NSValue(time: time3), NSValue(time: time4), NSValue(time: time5), NSValue(time: time6), NSValue(time: time7)]) { (time, image, time1, result, err) in
if let err = err {
print("there's an error in retrieving the images", err)
}
let theImage = UIImage(cgImage: image!)
imageArray.append(theImage)
if(result == .succeeded){
completion(imageArray)
}
}
}
由于每次创建新图像时都会调用该函数的完成处理程序,因此completion()
会多次调用该函数的完成处理程序。
我想实现completion()
仅在创建所有图像(在本例中为 7)之后才调用它。我该怎么做?