讓使用者從相簿挑一張圖,或現場拍一張照,幾乎是每個 App 都會遇到的需求。iOS 把這件事濃縮進 UIImagePickerController——一個同時能瀏覽相簿與啟動相機的系統元件。本文以一個可運行的完整範例走過整個流程。
放棄 xib、以純程式碼建立介面時,AppDelegate.m 大致如下:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
self.window.rootViewController = [[dateViewController alloc] init];
[self.window makeKeyAndVisible];
return YES;
}
dateViewController.h 中,我們需要一個 UIImageView 顯示結果,一個 UIImagePickerController 負責挑選,並遵循兩個 delegates:
#import <UIKit/UIKit.h>
@interface dateViewController : UIViewController
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, retain) UIImageView *imageview1;
@property (nonatomic, retain) UIImagePickerController *imagepicker;
@end
注意 UIImagePickerController 是 UINavigationController 的子類,因此 delegate 協定必須寫 UINavigationControllerDelegate,這是最常被漏掉的一行。
- (void)viewDidLoad
{
[super viewDidLoad];
// 1. 準備一個顯示圖片的視圖
imageview1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 50, 300, 200)];
imageview1.backgroundColor = [UIColor yellowColor];
[self.view addSubview:imageview1];
// 2. 從網路抓一張圖並顯示
NSURL *url = [NSURL URLWithString:@"https://www.google.com.hk/images/srpr/logo11w.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
imageview1.image = image;
// 3. 轉成 JPEG 資料並存檔到相簿
NSData *imageData = UIImageJPEGRepresentation(image, 1);
NSLog(@"%d", imageData.length);
UIImageWriteToSavedPhotosAlbum(image, self,
@selector(image:didFinishSavingWithError:contextInfo:), NULL);
// 4. 「訪問相冊」按鈕
UIButton *buttonPhoto = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonPhoto.tag = 100;
buttonPhoto.frame = CGRectMake(50, 250, 80, 50);
[buttonPhoto setTitle:@"訪問相冊" forState:UIControlStateNormal];
[buttonPhoto addTarget:self action:@selector(look:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buttonPhoto];
// 5. 「訪問攝像頭」按鈕
UIButton *buttonCamera = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonCamera.tag = 200;
buttonCamera.frame = CGRectMake(50, 310, 80, 50);
[buttonCamera setTitle:@"訪問攝像頭" forState:UIControlStateNormal];
[buttonCamera addTarget:self action:@selector(look:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buttonCamera];
}
同一個 action 透過 tag 區分來源,是最省事的寫法:
- (void)look:(UIButton *)button
{
if (button.tag == 100) {
// 相簿
imagepicker = [[UIImagePickerController alloc] init];
imagepicker.delegate = self;
imagepicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imagepicker animated:YES completion:nil];
} else {
// 相機:先確認裝置是否具備後置鏡頭
BOOL isCameraAvailable = [UIImagePickerController
isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
if (!isCameraAvailable) {
NSLog(@"沒有攝像頭");
return;
}
imagepicker = [[UIImagePickerController alloc] init];
imagepicker.delegate = self;
imagepicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagepicker.allowsEditing = YES;
[self presentViewController:imagepicker animated:YES completion:nil];
}
}
關鍵提醒:相機功能只能在真機上測試,模擬器沒有鏡頭,isCameraDeviceAvailable: 會回傳 NO。
PhotoLibrary:完整相簿,可多層瀏覽Camera:啟動相機拍照SavedPhotosAlbum:只看相機膠卷(第一層),使用者無法再往下翻#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// UIImagePickerControllerOriginalImage:原始圖片
// UIImagePickerControllerEditedImage:裁剪後的圖片
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
imageview1.image = image;
NSLog(@"info = %@", info);
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo
{
NSLog(@"error = %@", error);
}
這個範例寫於 iOS 7 時代,仍能運行,但有幾點值得更新:
改用 Photos 框架。存取相簿請改用 PHPhotoLibrary 與 PHAsset,並在 Info.plist 宣告 NSPhotoLibraryUsageDescription;相機則需要 NSCameraUsageDescription。缺少這些說明文字,App 會直接崩潰。
主執行緒與錯誤處理。dataWithContentsOfURL: 是同步呼叫,會阻塞主執行緒,正式專案請改用 NSURLSession。
EditedImage 可能為 nil。當 allowsEditing 為 NO 時,UIImagePickerControllerEditedImage 取不到值,應以 OriginalImage 作為後備。
PHPickerViewController。iOS 14 之後,系統推薦改用 PHPickerViewController,它執行在獨立程序中,不需要相簿權限即可選圖,隱私性更好。