iOS 调用系统相机和相册

电脑杂谈  发布时间:2019-09-09 21:07:15  来源:网络整理

强制打开相册 ios_ios 相机相册图片上传_强制进入相机 相册 ios

调用手机自拍并获得照片和开启平台相册获取照片是我们常常看到的常见功能。其实很做出来非常简洁,几步即可。

在info.plist文件中添加对照相机和相册获取的权限强制进入相机 相册 ios,如下图

ios 相机相册图片上传_强制打开相册 ios_强制进入相机 相册 ios

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

强制进入相机 相册 ios_ios 相机相册图片上传_强制打开相册 ios

@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,并在代理中推动相应步骤,如下

ios 相机相册图片上传_强制进入相机 相册 ios_强制打开相册 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];
}

根据不同的需求设定类别即可,如下:

强制进入相机 相册 ios_强制打开相册 ios_ios 相机相册图片上传

- (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

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...