應用中有時我們會有保存圖片的需求,如利用UIImagePickerController用IOS設備內置的相機拍照,或是有時我們在應用程序中利用UIKit的 UIGraphicsBeginImageContext,UIGraphicsEndImageContext,UIGraphicsGetImageFromCurrentImageContext方法創建一張圖像需要進行保存。 IOS的UIKit Framework提供了UIImageWriteToSavedPhotosAlbum方法對圖像進行保存,該方法會將image保存至用戶的相冊中,描述如下:
1
void UIImageWriteToSavedPhotosAlbum (
2
UIImage? *image,
3
id? ? ? completionTarget,
4
SEL? ? ? completionSelector,
5
void? ? *contextInfo
6
);參數說明:
image
帶保存的圖片UImage對象
completionTarget
圖像保存至相冊后調用completionTarget指定的selector(可選)
completionSelector
completionTarget的方法對應的選擇器,相當于回調方法,需滿足以下格式
- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo; ? ? ? ?contextInfo指定了在回調中可選擇傳入的數據。
當我們需要異步獲得圖像保存結果的消息時,我們需要指定completionTarget對象以及其completionSelector對應的選擇器。示例如下:
- (void)saveImageToPhotos:(UIImage*)savedImage
{
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 指定回調方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
NSString *msg = nil ;
if(error != NULL){
msg = @"保存圖片失敗" ;
}else{
msg = @"保存圖片成功" ;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存圖片結果提示"
message:msg delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alert show];
}
// 調用示例
UIImage *savedImage = [UIImage imageNamed:"savedImage.png"];
[self saveImageToPhotos:savedImage];