首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UIImagePickerController 拍照後儲存到相簿:實現代理方法

     編輯:程式設計綜合問答

缺少關鍵步驟

僅設定 sourceType = Camera 並呈現選取器,拍照完成後若未實現代理方法,圖片不會自動存入相簿。

完整實現

// 1. 遵守協議
@interface ViewController () 
@end

// 2. 呈現選取器
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self; // 關鍵:設定代理
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.showsCameraControls = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

// 3. 實現代理:使用者完成拍照
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    // 儲存到相簿
    UIImageWriteToSavedPhotosAlbum(image, self,
        @selector(image:didFinishSavingWithError:contextInfo:), nil);
    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 4. 儲存完成回調
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
        error ? @"失敗" : @"成功"
        message:error ? @"無法儲存" : @"已儲存到相簿"
        delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
    [alert show];
}

// 5. 使用者取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

關鍵點

  • picker.delegate = self 必須設定
  • UIImageWriteToSavedPhotosAlbum 非同步儲存,透過 selector 回調結果
  • 完成或取消後必須 dismissViewControllerAnimated 關閉選取器
  • Info.plist 需加入 NSCameraUsageDescription、NSPhotoLibraryAddUsageDescription
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved