可以尝试在生成UIImage时添加一个检查空值的代码,以此确认每个CGImage是否有效。另外也可以尝试增加请求图片的时长范围,以便获取更全面准确的信息。以下为代码示例:
let asset = AVURLAsset(url: url)
let generator = AVAssetImageGenerator(asset: asset)
// 设置图片时间范围,这里设置为整个视频的时间范围
let duration = asset.duration
let timeRange = CMTimeRange(start: .zero, end: duration)
generator.requestedTimeToleranceAfter = CMTime.zero
generator.requestedTimeToleranceBefore = CMTime.zero
var images: [UIImage] = []
// 实际生成图片的代码
do {
let cgImage = try generator.copyCGImage(at: time, actualTime: nil)
if cgImage != nil {
let image = UIImage(cgImage: cgImage!)
images.append(image)
}
} catch let error as NSError {
print("生成图片失败: \(error.localizedDescription)")
}