從攝像頭獲取照片和視頻
UIImagePickerController
-
可通過
UIImagePickerController
獲取視頻- 錄制長達30min的視頻
- 將視頻文件路徑以
NSString
形式傳遞給應(yīng)用程序
可設(shè)置使用前置或后置攝像頭菠净,是否使用LED燈祟剔,是否允許用戶裁剪或調(diào)整照片或視頻
-
工作方式:
- 創(chuàng)建實例
- 根據(jù)需要配置選取器
- 選取器包含一個符合
UIImagePickerControllerDelegate
協(xié)議的委托對象 - 當前的視圖控制器通常會調(diào)用
presentViewController:animated:completion:
,所以視圖控制器呈現(xiàn)為模態(tài) - 用戶完成照片或視頻后乡小,委托對象接收
imagePickerController:didFinishPickingMediaWithInfo:
消息- 后者接收一個字典,包含用戶獲取的媒體信息
- 原始或編輯過的照片
- 視頻文件位置
- 或其他有用信息
- 需調(diào)用
dismissViewControllerAnimated:completion:
釋放圖片選取器
- 后者接收一個字典,包含用戶獲取的媒體信息
- 用戶選擇取消圖片選擇器鹉梨,委托對象接收
imagePickerControllerDidCancel:
- 需調(diào)用
dismissViewControllerAnimated:completion:
釋放圖片選取器常柄,否則,取消按鈕不會起任何作用
- 需調(diào)用
-
判斷有哪些攝像頭可用
+ isSourceTypeAvailable:
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { //攝像頭存在至少一個攝像頭 }else { //攝像頭不可用 }
-
判斷前置或后置攝像頭是否可用
+ isCameraDeviceAvailable:
if([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllercameraDeviceFront]) { //前置攝像頭可用 } if([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) { //后置攝像頭可用 }
-
拍照實例部分代碼
- (IBAction)takePhoto:(id)sender { UIImagePickerController *pickerController = [[UIImagePickerController alloc]init]; if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { //設(shè)置視圖控制器控制攝像頭 pickerController.sourceType = UIImagePickerControllerSourceTypeCamera; if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) { pickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront; }else{ pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear; } pickerController.delegate = self; //將當前的視圖控制器拿掉 [self presentViewController:pickerController animated:YES completion:nil]; } } //視圖控制器的UIImagePickerControllerDelegate方法 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; self.imageView.image = image; [picker dismissViewControllerAnimated:YES completion:nil]; } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; }