最近使用Swift編程中帘睦,遇到一個(gè)問題,就是出現(xiàn)了 Call can throw, but it is not marked with 'try' and the error is not handled 的錯(cuò)誤坦康。
需要獲取視頻的某一幀的圖片竣付,使用copyCGImageAtTime(requestedTime: CMTime, actualTime: UnsafeMutablePointer<CMTime>) throws -> CGImage
但是使用該方法時(shí)出現(xiàn)了錯(cuò)誤:Call can throw, but it is not marked with 'try' and the error is not handled , 剛開始以為是參數(shù)的錯(cuò)誤,因?yàn)樵贠C里面方法是這樣的 - (nullable CGImageRef)copyCGImageAtTime:(CMTime)requestedTime actualTime:(nullable CMTime *)actualTime error:(NSError * __nullable * __nullable)outError
首先先看一下這個(gè)方法的作用是什么滞欠?
// 獲取單幀的圖片
- (nullable CGImageRef)copyCGImageAtTime:(CMTime)requestedTime actualTime:(nullable CMTime *)actualTime error:(NSError * __nullable * __nullable)outError
// 根據(jù)視頻的路徑獲取單幀圖片
- (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中這是一個(gè)很常見的方法古胆,但轉(zhuǎn)到Swift里面,方法發(fā)生了一些變化筛璧,但原理是不變的逸绎,但是卻出現(xiàn)了問題妖滔,
問題截圖:
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<CMTime>) throws -> CGImage
這里出現(xiàn)的throws是個(gè)什么鬼啊桶良?? 怎樣解決呢沮翔?陨帆?
其實(shí)很簡(jiǎn)單,原因就是沒有處理錯(cuò)誤 采蚀。我們根據(jù)錯(cuò)誤提示疲牵,調(diào)用可以拋出,但它沒有標(biāo)記和錯(cuò)誤處理通過加一個(gè)try解決榆鼠。
(PS: 就像Java中的異常錯(cuò)誤處理纲爸,也是采用 try ...catch)
下面是最終解決錯(cuò)誤的代碼:
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
}