拍照在App中使用頻次高,入門級(jí)別直接調(diào)用系統(tǒng)拍照
-
思路:
系統(tǒng)拍照使用UIImagePickerController
1.設(shè)置下plist裆装,否則沒權(quán)限踱承,報(bào)錯(cuò)
2.判斷攝像頭,獲取權(quán)限哨免,否則彈出界面黑著
3.設(shè)置代理茎活,實(shí)現(xiàn)代理
4.代理方法中獲取拍照的圖片/視頻
-
上菜
plist中添加Privacy - Camera Usage Description,文案根據(jù)App需要來
權(quán)限
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { }
- 設(shè)置UIImagePickerController
UIImagePickerController *vc = [[UIImagePickerController alloc] init]; // 設(shè)置該屬性的時(shí)候琢唾,出現(xiàn)拍照與拍視頻選項(xiàng) vc.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera]; vc.sourceType = UIImagePickerControllerSourceTypeCamera; vc.delegate = self; vc.allowsEditing = NO; // 設(shè)置攝像頭[后置攝像頭] vc.cameraDevice = UIImagePickerControllerCameraDeviceRear; // 設(shè)置閃光模式 vc.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto; // 設(shè)置攝像頭模式 vc.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo; // 當(dāng)該模式設(shè)置為video的時(shí)候载荔,meidaTypes設(shè)置出現(xiàn)拍照與拍視頻選項(xiàng)時(shí),先展示video視頻拍攝選項(xiàng) // 錄制的最大時(shí)間 vc.videoMaximumDuration = 10; // 視頻質(zhì)量 vc.videoQuality = UIImagePickerControllerQualityTypeHigh; vc.modalPresentationStyle = UIModalPresentationFullScreen; [[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:vc animated:YES completion:nil];
- 代理實(shí)現(xiàn)
#pragma mark - UINavigationControllerDelegate, UIImagePickerControllerDelegate - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info { // 獲取選中資源類型 NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) { // 拍照結(jié)果 UIImage *image = nil; if (picker.allowsEditing) { image = [info objectForKey:UIImagePickerControllerEditedImage]; } else { image = [info objectForKey:UIImagePickerControllerOriginalImage]; } [picker dismissViewControllerAnimated:YES completion:nil]; } else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) { // 視頻結(jié)果 NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL]; // 視頻存放到系統(tǒng)相冊(cè) [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { if (status == PHAuthorizationStatusAuthorized) { [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url]; } completionHandler:^(BOOL success, NSError * error) { if (success) { NSLog(@"保存視頻到相冊(cè)"); } else { NSLog(@"保存視頻到相冊(cè)失敳商摇:%@", error); } }]; } else { NSLog(@"無訪問相冊(cè)權(quán)限"); } dispatch_async(dispatch_get_main_queue(), ^{ [picker dismissViewControllerAnimated:YES completion:nil]; }); }]; } } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; }
-
結(jié)語:
UIImagePickerController使用方便懒熙,可拍照、視頻普办。適用于拍照界面無定制工扎、簡(jiǎn)單取圖這類需求