最近使用Swift编程中,遇到一个问题,就是出现了 Call can throw, but it is not marked with 'try' and the error is not handled 的错误。
需要获取视频的某一帧的图片,使用copyCGImageAtTime(requestedTime: CMTime, actualTime: UnsafeMutablePointer
但是使用该方法时出现了错误:Call can throw, but it is not marked with 'try' and the error is not handled , 刚开始以为是参数的错误,因为在OC里面方法是这样的 - (nullable CGImageRef)copyCGImageAtTime:(CMTime)requestedTime actualTime:(nullable CMTime *)actualTime error:(NSError * __nullable * __nullable)outError
首先先看一下这个方法的作用是什么?
// 获取单帧的图片
- (nullable CGImageRef)copyCGImageAtTime:(CMTime)requestedTime actualTime:(nullable CMTime *)actualTime error:(NSError * __nullable * __nullable)outError
// 根据视频的路径获取单帧图片
- (UIImage *)getThumbImage:(NSURL *)url {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
gen.appliesPreferredTrackTransform = YES;
CMTime time = CMTimeMakeWithSeconds(0.0, 1);
NSError *error = nil;
CMTime actualTime;
CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
return thumb;
}
在OC中这是一个很常见的方法,但转到Swift里面,方法发生了一些变化,但原理是不变的,但是却出现了问题,
问题截图:
swift里面方法是这样的
/*!
@method copyCGImageAtTime:actualTime:error:
@abstract Returns a CFRetained CGImageRef for an asset at or near the specified time.
@param requestedTime The time at which the image of the asset is to be created.
@param actualTime A pointer to a CMTime to receive the time at which the image was actually generated. If you are not interested in this information, pass NULL.
@param outError An error object describing the reason for failure, in the event that this method returns NULL.
@result A CGImageRef.
@discussion Returns the CGImage synchronously. Ownership follows the Create Rule. */
public func copyCGImageAtTime(requestedTime: CMTime, actualTime: UnsafeMutablePointer) throws -> CGImage
这里出现的throws是个什么鬼啊?? 怎样解决呢??
其实很简单,原因就是没有处理错误 。我们根据错误提示,调用可以抛出,但它没有标记和错误处理通过加一个try解决。
(PS: 就像Java中的异常错误处理,也是采用 try ...catch)
下面是最终解决错误的代码:
func getThunbImage(url: NSURL) -> (UIImage) {
let asset: AVURLAsset = AVURLAsset(URL: url, options: nil)
let gen: AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
gen.appliesPreferredTrackTransform = true
let time: CMTime = CMTimeMakeWithSeconds(0, 1)
var actualTime: CMTime = CMTimeMake(0, 0)
var thumb: UIImage = UIImage()
do {
let image: CGImageRef = try gen.copyCGImageAtTime(time, actualTime: &actualTime)
thumb = UIImage(CGImage: image)
} catch { }
return thumb
}