Xcode8打开系统相册和摄像头的方法

本文介绍如何在iOS应用中正确处理照片库和相机的权限请求,并提供了使用UIImagePickerController从相册选择图片或通过相机拍摄图片的具体实现步骤。

一、跟以往最主要的区别在于,需要进行info.plist授权操作,具体如下:

1,相册。NSPhotoLibraryUsageDescription

<key>NSPhotoLibraryUsageDescription</key>

    <string> App 需要您的同意才能打开您的相册(此处可以随便写提示的内容)</string>


2,相机。NSCameraUsageDescription

<key>NSCameraUsageDescription</key>

    <string>App 需要您的同意才能打开您的相机(此处可以随便写提示的内容)</string>

二、下面就是基础的打开相册和摄像头的方法了

1,导入头文件

#import "VPImageCropperViewController.h"

#import <MobileCoreServices/MobileCoreServices.h>

#import <AssetsLibrary/AssetsLibrary.h>

#import "UIImage+Resize.h"

#import "SVProgressHUD.h"

2,实现相应的委托

UIImagePickerControllerDelegate,UIActionSheetDelegate,VPImageCropperDelegate,UINavigationControllerDelegate

3,添加相应的代码

#pragma mark  --设置头像事件

//设置头像事件

-(void)setUserIcon

{

    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 8)

    {

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

        

        UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

            

            [self goToImagePicker:YES];

            

            

            //

        }];

        

        [alert addAction:takePhotoAction];

        

        

        UIAlertAction *imageLibAction = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

            

            

            

            [self goToImagePicker:NO];

            

        }];

        

        [alert addAction:imageLibAction];

        

        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){

            

            

        }];

        

        [alert addAction:cancelAction];

        

        //        [alert.view setTintColor:UIColorFromRGB(0x50c878)];

        

        [self presentViewController:alert animated:YES completion:nil];

        

    }

    else{

        

        UIActionSheet* _actionSheet = [[UIActionSheet alloc]

                                       initWithTitle:nil

                                       delegate:self

                                       cancelButtonTitle:@"取消"

                                       destructiveButtonTitle:nil

                                       otherButtonTitles:@"拍照", /*@"从相册选择",*/nil];

        

        [_actionSheet showInView:self.view];

        

    }

    

}


#pragma mark - 选相片代理

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

{

    // 导入图片 or 拍照

    if(buttonIndex == 0)

    {

        [self goToImagePicker:YES];

        

    }

    else if(buttonIndex == 1){

        [self goToImagePicker:NO];

        

    }

}


//yes:照相机    no:相册

-(void)goToImagePicker:(BOOL)camera

{

    if (camera) {

        

        self.isCamera=YES;

        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

        {

            //             [PublishVC goToCamera:self delegate:self];

            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

            {

                UIImagePickerController *controller = [[UIImagePickerController alloc] init];

                controller.sourceType = UIImagePickerControllerSourceTypeCamera;

                //[controller setVideoQuality:UIImagePickerControllerQualityTypeLow];

                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];

                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];

                controller.mediaTypes = mediaTypes;

                controller.delegate = self;

                [self presentViewController:controller

                                   animated:YES

                                 completion:^(void){

                                 }];

                

                

                

            }

            

        }

        

    }

    else{

        

        self.isCamera=NO;

        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])

        {

            UIImagePickerController *controller = [[UIImagePickerController alloc] init];

            controller.sourceTypeUIImagePickerControllerSourceTypePhotoLibrary;

            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];

            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];

            controller.mediaTypes = mediaTypes;

            controller.delegate = self;

            [self presentViewController:controller

                               animated:YES

                             completion:^(void){

                             }];

            

            

        }

        

    }

}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    [picker dismissViewControllerAnimated:YES completion:^() {

        

        UIImage *editedImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

        

        if (self.isCamera) {

            if (editedImage.size.width > SIZE_AVATAR) {

                self.imageToSave = [editedImage resizedImage:CGSizeMake(SIZE_AVATAR, SIZE_AVATAR) interpolationQuality:kCGInterpolationDefault];

            }

            else

            {

                self.imageToSave = editedImage;

            }

            

            NSLog(@"1");

            //提示框

            [SVProgressHUD  showSuccessWithStatus:@"正在上传图片"];

            //调用设置头像接口和刷新UI

            [self.indInfoTableView reloadData];

           }

        else{

            int wantedPhotoWidth = kScreenWidth;

            int clipHight = (kScreenHeight - wantedPhotoWidth) /2;

            VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:editedImage cropFrame:CGRectMake(0, clipHight, wantedPhotoWidth, wantedPhotoWidth) limitScaleRatio:3.0];

            imgEditorVC.delegate = self;

            [self presentViewController:imgEditorVC animated:NO completion:nil];

            NSLog(@"2");

        }

        

    }];

}



#pragma mark VPImageCropperDelegate

- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {

    

    self.imageToSave = nil;

   NSLog(@"3");

    //缩放图片

    if (editedImage.size.width > SIZE_AVATAR) {

        self.imageToSave = [editedImage resizedImage:CGSizeMake(SIZE_AVATAR, SIZE_AVATAR) interpolationQuality:kCGInterpolationDefault];

    }

    else

    {

        self.imageToSave = editedImage;

    }

    

    

    

    

    //提示框

    [SVProgressHUD  showSuccessWithStatus:@"正在上传图片"];

    

    

    //调用设置头像接口和刷新UI

    [cropperViewController dismissViewControllerAnimated:YES completion:^{

    }];

    

    [self.indInfoTableView reloadData];

}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController

{

    NSLog(@"4");

    [cropperViewController dismissViewControllerAnimated:YES completion:^{

    }];

    

}

此处的 self.imageToSave和self.isCamera分别是UIImage和Bool的两个属性值。

好了,至此就完成了基本的操作。



### 如何在 Xcode 中实现相机功能或访问设备摄像头 要在 Xcode 中实现相机功能或访问设备摄像头,需要完成以下几个方面的设置: #### 1. 配置 `Info.plist` 文件 在使用摄像头之前,必须向用户请求访问权限。这可以通过修改项目的 `Info.plist` 文件来实现。以下是需要添加的键及其描述[^1]: ```xml <key>NSCameraUsageDescription</key> <string>我们需要访问您的摄像头以提供此功能。</string> ``` 如果还需要访问相册,则可以额外添加以下键[^1]: ```xml <key>NSPhotoLibraryUsageDescription</key> <string>我们需要访问您的相册以保存拍摄的照片。</string> ``` #### 2. 使用 AVFoundation 框架访问摄像头 为了在 macOS 或 iOS 上访问摄像头并捕获图像数据,推荐使用 Apple 的 `AVFoundation` 框架。以下是一个简单的 Objective-C 实现示例[^2]: ##### 导入必要的头文件 ```objective-c #import <AVFoundation/AVFoundation.h> ``` ##### 创建会话并配置输入输出 ```objective-c // 初始化捕捉会话 AVCaptureSession *captureSession = [[AVCaptureSession alloc] init]; // 获取可用的摄像头设备 NSError *error = nil; AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo] error:&error]; if (input) { [captureSession addInput:input]; // 添加输入流 } else { NSLog(@"Error: %@", error); } // 设置预览图层 AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:captureSession]; previewLayer.frame = self.view.bounds; // 假设这是视图控制器中的主视图 [self.view.layer addSublayer:previewLayer]; // 开始运行会话 [captureSession startRunning]; ``` #### 3. 解决 OpenCV 访问 Mac 摄像头权限问题 如果计划使用 OpenCV 来访问摄像头,可能需要特别注意权限管理。具体步骤如下[^3]: - **配置 `Info.plist` 文件**:确保已添加 `Privacy - Camera Usage Description` 键,并为其赋值为合适的字符串说明。 - **放置 `.plist` 文件到正确位置**:新创建的 `.plist` 文件应位于可执行文件所在的同一目录。 #### 4. 使用 `UIImagePickerController` 打开系统相机 对于 iOS 应用程序,可以直接利用 `UIImagePickerController` 类来快速集成相机功能[^4]。以下是一个 Swift 示例代码片段: ```swift import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() } @IBAction func openCamera(_ sender: UIButton) { let imagePicker = UIImagePickerController() imagePicker.delegate = self if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePicker.sourceType = .camera present(imagePicker, animated: true, completion: nil) } else { print("相机不可用") } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { dismiss(animated: true, completion: nil) } } ``` #### 5. 特殊情况下的插件依赖 如果有更复杂的需求(例如 AR 场景),可以选择使用第三方插件辅助开发。例如,在 Unity visionOS 平台上构建应用程序时,可能会涉及 `EnterpriseCameraAccessPlugin` 插件包的相关配置[^5]。 --- ### 总结 以上介绍了多种方式实现在 Xcode 中开启相机功能的方法,包括手动配置 `AVFoundation`、调整 `Info.plist` 文件以及直接调用系统的 `UIImagePickerController` 组件等技术手段。每种方案适用于不同的需求背景技术栈,请根据实际项目需求选择合适的技术路径。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值