本文主要是介绍IOS 调用照相机、相册功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先需要导入<AssetsLibrary/AssetsLibrary.h>、<Photos/Photos.h>这两个框架,然后遵循UIImagePickerControllerDelegate。
调用相册
#pragma mark 选择图片
- (void)selectPhoto
{if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusRestricted || [PHPhotoLibrary authorizationStatus] == AVAuthorizationStatusDenied) {NSString *appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];if (!appName) appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];NSString *info = [NSString stringWithFormat:@"请在%@的\"设置-隐私-照片\"选项中,\r允许%@访问你的手机相册。",[UIDevice currentDevice].model,appName];UIAlertView *showAlert = [[UIAlertView alloc] initWithTitle:nil message:info delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];[showAlert show];}else {//1.首先判断照片源是否可用if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {//2.实例化UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];//2.1设置照片源imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//2.2是否允许修改imagePicker.allowsEditing = YES;//2.3设置代理imagePicker.delegate = self;//2.4显示控制器[self presentViewController:imagePicker animated:YES completion:nil];}}
}
调用照相机
#pragma mark 拍照
- (void)takePhoto
{AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {NSString *appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleDisplayName"];if (!appName) appName = [[NSBundle mainBundle].infoDictionary valueForKey:@"CFBundleName"];NSString *info = [NSString stringWithFormat:@"请在%@的\"设置-隐私-相机\"选项中,\r允许%@访问你的照相机。",[UIDevice currentDevice].model,appName];UIAlertView *showAlert = [[UIAlertView alloc] initWithTitle:nil message:info delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];[showAlert show];} else { // 调用相机if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;imagePicker.allowsEditing = YES;imagePicker.delegate = self;[self presentViewController:imagePicker animated:YES completion:nil];}}
}
代理方法
#pragma mark - UIImagePickerController代理
#pragma mark 完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{UIImage *image = info[@"UIImagePickerControllerEditedImage"];[picker dismissViewControllerAnimated:YES completion:nil];
}#pragma mark 取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{[picker dismissViewControllerAnimated:YES completion:nil];
}
这篇关于IOS 调用照相机、相册功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!