Swift中Call can throw, but it is not marked with 'try' and the error is not handled錯誤的解決

最近使用Swift編程中,遇到一個問題,就是出現了 Call can throw, but it is not marked with 'try' and the error is not handled 的錯誤。
需要獲取視頻的某一幀的圖片,使用copyCGImageAtTime(requestedTime: CMTime, actualTime: UnsafeMutablePointer<CMTime>) throws -> CGImage 但是使用該方法時出現了錯誤: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<CMTime>) 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 
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容