預設情況下,UIImagePickerController 開啟相機後只能拍照或只能錄影,取決於你設定的 mediaTypes。但只要把兩種媒體型別一起放進陣列,系統就會在取經界面同時提供「照片」與「錄影」兩個切換標籤,讓使用者自行選擇。
關鍵程式碼如下:
- (void)recordVideo:(id)sender {
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
ipc.delegate = self;
ipc.allowsEditing = YES;
ipc.videoQuality = UIImagePickerControllerQualityTypeMedium;
ipc.videoMaximumDuration = 30.0f; // 最長 30 秒
// 只指定 public.movie 時,介面只會有錄影
// ipc.mediaTypes = [NSArray arrayWithObject:@"public.movie"];
// 同時放入兩者,介面就會並列「錄影」與「拍照」
ipc.mediaTypes = [NSArray arrayWithObjects:@"public.movie", @"public.image", nil];
[self presentModalViewController:ipc animated:YES];
}
這裡幾個屬性的作用值得逐一釐清:
别忘了實作 delegate,否則按下完成後畫面會關掉卻拿不到任何資料:
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:UIImagePickerControllerMediaTypeImage]) {
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
if (image == nil) {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
// 處理照片
}
else if ([mediaType isEqualToString:UIImagePickerControllerMediaTypeMovie]) {
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
// 處理影片:videoURL 指向暫存目錄中的檔案
}
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated:YES];
}
第一,一定要用 mediaType 判斷型別。因為使用者可能選拍照也可能選錄影,若無條件地當成圖片處理,選到影片時會拿到 nil 而崩潰。
第二,影片檔案在暫存目錄,必須自行搬走。UIImagePickerControllerMediaURL 回傳的路徑位於 app 的 tmp 目錄,系統隨時可能清理。若你需要長期保存,必須在委派中立刻把它複製到 Documents 或 Library 底下。
另外要補上隱私權限說明。iOS 10 之後,存取相機與相簿都要求在 Info.plist 中提供用途說明字串(NSCameraUsageDescription、NSPhotoLibraryUsageDescription),缺少任一項,App 在執行到取經器時會直接崩潰。本文示範用的是 presentModalViewController: 與 dismissModalViewControllerAnimated:,這組 API 在 iOS 6 之後已被取代,新專案請改用 presentViewController:animated:completion:。