Xcode8中用UIImageWriteToSavedPhotosAlbum方法将圖檔寫入相冊:
當使用這個方法寫入圖檔的時候,發現以前使用的方法調用會報錯,這裡就寫出
我改正後所使用的方法:
UIImageWriteToSavedPhotosAlbum(image: UIImage, completionTarget: AnyObject?, completionSelector: Selector, contextInfo: UnsafeMutablePointer<Void>)
這個是系統的方法,先來解釋下各個參數:
1.image:将要儲存的圖檔
2.completionTarget:儲存完畢後,回調方法所在的對象
3.completionSelector:儲存完畢後,回調的方法
4.contextInfo:可選參數
需要注意的是completionSelector這個方法并不是随便瞎寫的,蘋果官方建議我們使用如下方法:
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
其實使用的方法名倒不是很重要,可以随意取,但是參數必須要有上面的3個。
在OC中還好說但是在Swift用此方法就會遇到坑。如何聲明此方法是關鍵:
這裡我采用的是#selector(target.method)的方式進行聲明的,具體代碼如下:
UIImageWriteToSavedPhotosAlbum(image!, self, #selector(SLPictureBrowserController.savedPhotosAlbum(_:didFinishSavingWithError:contextInfo:)), nil)
前面的SLPictureBrowserController就是target。
方法的具體實作就是:
//儲存圖檔
func savedPhotosAlbum(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
if error != nil {
SVProgressHUD.showErrorWithStatus("儲存失敗!")
SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
delay(1.0)
} else {
SVProgressHUD.showSuccessWithStatus("儲存成功!")
SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
//延遲1秒消失
delay(1.0)
}
}
//延遲1秒消失
private func delay(time: NSTimeInterval) {
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC)) )
dispatch_after(delay, dispatch_get_main_queue(), {
SVProgressHUD.dismiss()
})
}