
调用手机自拍并获得照片和开启平台相册获取照片是我们常常看到的常见功能。其实很做出来非常简洁,几步即可。
在info.plist文件中添加对照相机和相册获取的权限强制进入相机 相册 ios,如下图


初始化UIImagePickerController ,并添加相应修改,如下

@property (strong, nonatomic) UIImagePickerController *picker;
------------------------------------------------------------
self.picker.delegate = self;
self.picker.allowsEditing = YES;
------------------------------------------------------------
- (UIImagePickerController *)picker
{
if (!_picker) {
_picker = [[UIImagePickerController alloc]init];
}
return _picker;
}
需要添加UIImagePickerControllerDelegate和UINavigationControllerDelegate这两个代理强制进入相机 相册 ios,并在代理中推动相应步骤,如下

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
// 获取图片
UIImage *image = info[UIImagePickerControllerOriginalImage];
self.image.image = image;
// 获取图片后返回
[picker dismissViewControllerAnimated:YES completion:nil];
}
//按取消按钮时候的功能
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
// 返回
[picker dismissViewControllerAnimated:YES completion:nil];
}
根据不同的需求设定类别即可,如下:

- (IBAction)buttonAction:(UIButton *)sender {
BOOL isPicker = NO;
switch (sender.tag) {
case 10000:
// 打开相机
isPicker = true;
// 判断相机是否可用
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
isPicker = true;
}
break;
case 10001:
// 打开相册
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
isPicker = true;
break;
default:
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
isPicker = true;
break;
}
if (isPicker) {
[self presentViewController:self.picker animated:YES completion:nil];
}else {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误" message:@"相机不可用" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
}
}
希望这篇文章对大家看官有所帮助,Demo下载地址:Demo
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/ruanjian/article-122316-1.html
有利益就有冲突
支持你
加油