博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一行代码打开相册/相机
阅读量:6252 次
发布时间:2019-06-22

本文共 8217 字,大约阅读时间需要 27 分钟。

代码地址如下:

http://www.demodashi.com/demo/11634.html

一、前言

当我们想要打开相机/相册的时候,如果是没有授权过的话,那么就会弹出这样的界面,是不是很丑啊,所以QQ等应用在没有授权的时候,会弹出一个Alert来提醒用户,没有打开权限,这样既可以告诉用户如何打开界面,又可以不显示这种未授权的界面样式,提高了用户的体验。

相册未授权界面

相机未授权界面

二、效果图:

效果图.gif

三、代码实现:

只需要一行代码即可打开相册/相机ViewController.m文件

#import "ViewController.h"#import "CFLibraryAndCamera.h"#define kScreen [UIScreen mainScreen].bounds.size@interface ViewController () 
@property (nonatomic,strong) CFLibraryAndCamera *libraryandCamera;@property (nonatomic,strong) UIImageView *bgimv;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.title = @"权限问题"; self.view.backgroundColor = [UIColor whiteColor]; _bgimv = [[UIImageView alloc]init]; _bgimv.center = CGPointMake(kScreen.width*0.5, 164+30); _bgimv.bounds = CGRectMake(0, 0, 200, 200); _bgimv.backgroundColor = [UIColor grayColor]; _bgimv.contentMode = UIViewContentModeScaleAspectFit; [self.view addSubview:_bgimv]; UIButton *picBtn = [[UIButton alloc]initWithFrame:CGRectMake(30, kScreen.height-150, kScreen.width-60, 50)]; [picBtn setTitle:@"选取照片" forState:UIControlStateNormal]; picBtn.backgroundColor = [UIColor blueColor]; [picBtn addTarget:self action:@selector(picBtnClike) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:picBtn]; UIButton *creamBtn = [[UIButton alloc]initWithFrame:CGRectMake(30, kScreen.height-90, kScreen.width-60, 50)]; [creamBtn setTitle:@"选取相机" forState:UIControlStateNormal]; creamBtn.backgroundColor = [UIColor blueColor]; [creamBtn addTarget:self action:@selector(creamBtnClike) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:creamBtn];}#pragma mark - 自己创建的方法//懒加载创建-(CFLibraryAndCamera *)libraryandCamera{ if (!_libraryandCamera) { _libraryandCamera = [[CFLibraryAndCamera alloc]init]; _libraryandCamera.delegate = self; _libraryandCamera.allowsEditing = YES; } return _libraryandCamera;}//打开相册-(void)picBtnClike{ [self.libraryandCamera picBtnClike:self];}//打开相机-(void)creamBtnClike{ [self.libraryandCamera cameraBtnClike:self];}//消失界面-(void)dismissLibraryAndCameraPickingImage:(UIImage *)image editingInfo:(NSDictionary
*)editingInfo{ _bgimv.image = image;}//选择界面取消按钮点击-(void)didCancel{ NSLog(@">>>>>>>>>");}

只需要懒加载创建一个对象,然后调用对象的打开相册/相机方法即可

CFLibraryAndCamera.h文件

#import 
#import
@protocol CFLibraryAndCameraDelegate
//消失界面-(void)dismissLibraryAndCameraPickingImage:(UIImage *)image editingInfo:(NSDictionary
*)editingInfo;//选择界面取消按钮点击-(void)didCancel;@end//导入相册库 iOS7#import
//导入相册库 iOS8#import
//iOS10要在plist文件中增加//
NSPhotoLibraryUsageDescription
//
App需要您的同意,才能访问相册
//导入相机框架#import
//iOS10要在plist文件中增加//
NSCameraUsageDescription
//
App需要您的同意,才能访问相机
@interface CFLibraryAndCamera : NSObject
@property (nonatomic,strong) UIImagePickerController *imgPickerVC;@property (nonatomic,assign)id
delegate;/** 打开相册 */-(void)picBtnClike:(UIViewController *)viewController;/** 打开相机 */-(void)cameraBtnClike:(UIViewController *)viewController;/** 图片是否编辑 */@property (nonatomic,assign,getter=isAllowsEditing) BOOL allowsEditing;/** 判断设备是否有摄像头 */-(BOOL)isCameraAvailable;/** 前面的摄像头是否可用 */-(BOOL)isFrontCameraAvailable;/** 后面的摄像头是否可用 */-(BOOL)isRearCameraAvailable;

CFLibraryAndCamera.m文件

#import "CFLibraryAndCamera.h"@interface CFLibraryAndCamera() @end@implementation CFLibraryAndCamera-(UIImagePickerController *)imgPickerVC{    if (!_imgPickerVC) {        _imgPickerVC = [[UIImagePickerController alloc]init];        _imgPickerVC.delegate = self;    }    return _imgPickerVC;}#pragma mark - 属性设置-(void)setAllowsEditing:(BOOL)allowsEditing{    _allowsEditing = allowsEditing;    self.imgPickerVC.allowsEditing = _allowsEditing;}#pragma mark - 摄像头和相册相关的公共类// 判断设备是否有摄像头-(BOOL)isCameraAvailable{    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];}// 前面的摄像头是否可用-(BOOL)isFrontCameraAvailable{    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];}// 后面的摄像头是否可用-(BOOL)isRearCameraAvailable{    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];}/** 打开相机 */-(void)cameraBtnClike:(UIViewController *)viewController{    //判断相机是否可用    if (![self isCameraAvailable]) {        [self showAlertViewTitle:@"温馨提示" message:@"相机不可用" viewController:viewController];        return;    }        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];    /*     AVAuthorizationStatusNotDetermined  不确定(第一次打开)     AVAuthorizationStatusRestricted  受限制     AVAuthorizationStatusDenied  拒绝     AVAuthorizationStatusAuthorized  经授权     */    if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {        [self showAlertViewTitle:@"没有相机访问权限" message:@"请到设置中心设置权限\n设置->隐私->相机" viewController:viewController];    }        //打开相机    self.imgPickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;    [viewController presentViewController:self.imgPickerVC animated:YES completion:nil];}/** 打开相册 */-(void)picBtnClike:(UIViewController *)viewController{    if ([[[UIDevice currentDevice] systemVersion] floatValue] <8.0) {        //iOS7        ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];        /*         ALAuthorizationStatusNotDetermined  不确定(第一次打开)         ALAuthorizationStatusRestricted  受限制         ALAuthorizationStatusDenied  拒绝         ALAuthorizationStatusAuthorized  经授权         */        if (status == ALAuthorizationStatusRestricted || status ==ALAuthorizationStatusDenied) {            [self showAlertViewTitle:@"没有相册访问权限" message:@"请到设置中心设置权限\n设置->隐私->相机" viewController:viewController];        }            }else{        //iOS7以上        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];        /*         PHAuthorizationStatusNotDetermined  不确定(第一次打开)         PHAuthorizationStatusRestricted  受限制         PHAuthorizationStatusDenied  拒绝         PHAuthorizationStatusAuthorized  经授权         */        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {            [self showAlertViewTitle:@"没有相册访问权限" message:@"请到设置中心设置权限\n设置->隐私->照片" viewController:viewController];        }    }        //打开相册    self.imgPickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;    [viewController presentViewController:self.imgPickerVC animated:YES completion:nil];}/** 只带确定的alertView简单弹框  @param titleStr 标题 @param message 内容 */-(void)showAlertViewTitle:(NSString *)titleStr message:(NSString *)message viewController:(UIViewController *)viewController{    if ([[[UIDevice currentDevice] systemVersion] floatValue] <8.0) {        //iOS7        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:titleStr message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];        [alert show];        return;            }else{        //iOS7以上        UIAlertController *alert = [UIAlertController alertControllerWithTitle:titleStr message:message preferredStyle:UIAlertControllerStyleAlert];        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {                    }]];        //显示        [viewController presentViewController:alert animated:YES completion:nil];        return;    }}#pragma mark - UIImagePickerControllerDelegate/** 选取图片后执行方法 */- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary
*)editingInfo{ NSLog(@"%p",picker); [picker dismissViewControllerAnimated:YES completion:nil]; [self.delegate dismissLibraryAndCameraPickingImage:image editingInfo:editingInfo];}/** 点击取消执行方法 */- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ [picker dismissViewControllerAnimated:YES completion:nil]; [self.delegate didCancel];}
如果需要更改提示的内容,就在CFLibraryAndCamera.m文件中修改提示内容

四、代码结构截图:

第一层目录结构

UP11x3G8OG3OuMh9dya.png

第二层目录结构

IDJginHBYhr4UCxxmWg.png

一行代码打开相册/相机

代码地址如下:

http://www.demodashi.com/demo/11634.html

注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权

你可能感兴趣的文章
json字符串与json对象的相互转换
查看>>
APM最佳实践:Web 2.0和AJAX四大优化战略
查看>>
Java优先队列一些问题
查看>>
【转】varchar,nvarchar长度、性能、及所占空间分析
查看>>
python控制语句执行流程(for)
查看>>
[NOIP2017 TG D2T2]宝藏(模拟退火)
查看>>
评价反馈
查看>>
Only the original thread that created a view hierarchy can touch its views的解决方案
查看>>
linux Git版本控制学习与Git服务器搭建
查看>>
配置Mqtt
查看>>
风暴数码论坛教程--初识Android
查看>>
【转】PHP乱码问题,UTF-8(乱码)
查看>>
熟悉常用的Linux操作
查看>>
iOS网络加载图片缓存策略之ASIDownloadCache缓存优化
查看>>
SQL优化工具SQLAdvisor使用
查看>>
mysql 返回多列的方式
查看>>
php log类
查看>>
Android平台根据分辨率计算屏幕尺寸,基于物理尺寸来验证手机和平板应用合并的可行性...
查看>>
ASP.NET&AJAX&JSON - 动态读取数据
查看>>
如何理解Nginx, WSGI, Flask之间的关系
查看>>