iOS相册、相机、通讯录权限获取

一、为什么要获取权限

在越来越注重个人隐私的今天,用户很多情况下希望自己能完全掌握自己手机应用对媒体信息的一些访问权限,比如相册、相机、通讯录等。苹果在iOS7、iOS8等几个系统版本对一些权限的控制都做了加强,需要用户授权后应用才有相关的访问权限。

场景:

  • 在你获取相册数据的时候,如果用户拒绝授权,那么可能会获取不到数据,此时需要给用户相应的提示,告知用户是权限的问题,此时,就需要得知相应的权限状态给用户恰当的提示。

  • 用户的设备没有相机输入设备,如果你想访问用户的相机,此时就需要判断用户设备是否支持,给出恰当的提示。

二、权限状态说明

  • 相册、相机、通讯录等授权状态目前都有种,都可以对应以下几种状态:

    AuthorizationStatusNotDetermined      // 用户从未进行过授权等处理,首次访问相应内容会提示用户进行授权
    AuthorizationStatusAuthorized = 0,    // 用户已授权,允许访问
    AuthorizationStatusDenied,            // 用户拒绝访问
    AuthorizationStatusRestricted,        // 应用没有相关权限,且当前用户无法改变这个权限,比如:家长控制
    

三、权限获取

  1. 相册权限
  • 是否支持

     ``` 
     [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]
     ```     
    
  • 获取权限状态

     ios8以前
     
     ```
         ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
     ```
     
     ios8及以后
     
     ```
         PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
     ```
    
  • 请求权限

     ```
     [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                     }];
     ```
    
  • 权限状态

     iOS8以前
     
     ```
     typedef NS_ENUM(NSInteger, ALAuthorizationStatus) {
         ALAuthorizationStatusNotDetermined NS_ENUM_DEPRECATED_IOS(6_0, 9_0) = 0, // User has not yet made a choice with regards to this application
         ALAuthorizationStatusRestricted NS_ENUM_DEPRECATED_IOS(6_0, 9_0),        // This application is not authorized to access photo data.
                                                 // The user cannot change this application’s status, possibly due to active restrictions
                                                 //  such as parental controls being in place.
         ALAuthorizationStatusDenied NS_ENUM_DEPRECATED_IOS(6_0, 9_0),            // User has explicitly denied this application access to photos data.
         ALAuthorizationStatusAuthorized NS_ENUM_DEPRECATED_IOS(6_0, 9_0)        // User has authorized this application to access photos data.
     } NS_DEPRECATED_IOS(6_0, 9_0, "Use PHAuthorizationStatus in the Photos framework instead");
     ```
     
     iOS8及以后
     
     ```
     typedef NS_ENUM(NSInteger, PHAuthorizationStatus) {
         PHAuthorizationStatusNotDetermined = 0, // User has not yet made a choice with regards to this application
         PHAuthorizationStatusRestricted,        // This application is not authorized to access photo data.
                                                 // The user cannot change this application’s status, possibly due to active restrictions
                                                 //   such as parental controls being in place.
         PHAuthorizationStatusDenied,            // User has explicitly denied this application access to photos data.
         PHAuthorizationStatusAuthorized         // User has authorized this application to access photos data.
     } NS_AVAILABLE_IOS(8_0);
     ```
    
  1. 拍照权限
  • 是否支持

     ```
     [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]
     ``` 
    
  • 获取权限状态

     ```
     AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
     ```
    
  • 请求权限

     ```
     [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                     }];
     ```
    
  • 权限状态

     ```
     typedef NS_ENUM(NSInteger, AVAuthorizationStatus) {
         AVAuthorizationStatusNotDetermined = 0,
         AVAuthorizationStatusRestricted,
         AVAuthorizationStatusDenied,
         AVAuthorizationStatusAuthorized
     } NS_AVAILABLE_IOS(7_0) __TVOS_PROHIBITED;
     ```
    
  1. 通讯录权限
  • 获取权限状态

     iOS9以前
     
     ```
     ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
     ```
     
     iOS9及以后
     
     ```
     CNAuthorizationStatus authStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
     ```
    
  • 请求权限

     iOS9以前
     
     ```
     __block ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
     if (addressBook == NULL) {
         [self executeCallback:callback status:WTAuthorizationStatusNotSupport];
         return;
     }
     ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
         if (granted) {
             // 成功
         } else {
             // 失败
         }
         if (addressBook) {
             CFRelease(addressBook);
             addressBook = NULL;
         }
     });
     ```
     
     iOS9及以后
     
     ```
     CNContactStore *contactStore = [[CNContactStore alloc] init];
     [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
         if (granted) {
             // 成功
         } else {
             // 失败
         }
     }];
     ```
    
  • 权限状态

     iOS9以前
     
     ```
     typedef CF_ENUM(CFIndex, ABAuthorizationStatus) {
         kABAuthorizationStatusNotDetermined = 0,    // deprecated, use CNAuthorizationStatusNotDetermined
         kABAuthorizationStatusRestricted,           // deprecated, use CNAuthorizationStatusRestricted
         kABAuthorizationStatusDenied,               // deprecated, use CNAuthorizationStatusDenied
         kABAuthorizationStatusAuthorized            // deprecated, use CNAuthorizationStatusAuthorized
     } AB_DEPRECATED("use CNAuthorizationStatus");
     ```
     
     iOS9及以后
     
     ```
     typedef NS_ENUM(NSInteger, CNAuthorizationStatus)
    

{
/*! The user has not yet made a choice regarding whether the application may access contact data. /
CNAuthorizationStatusNotDetermined = 0,
/
! The application is not authorized to access contact data.
* The user cannot change this application’s status, possibly due to active restrictions such as parental controls being in place. /
CNAuthorizationStatusRestricted,
/
! The user explicitly denied access to contact data for the application. /
CNAuthorizationStatusDenied,
/
! The application is authorized to access contact data. */
CNAuthorizationStatusAuthorized
} NS_ENUM_AVAILABLE(10_11, 9_0);
```

四、拒绝授权的处理

  • 用户拒绝授权后,如果访问相应内容可能会出现一些类似没有数据的情况,此时应该给用户提示,引导用户授权。

    跳转到应用设置:

    NSURL *settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:settingUrl]) {
        [[UIApplication sharedApplication] openURL:settingUrl];
    }
    

五、简单封装示例

  • 工具类

    WTAuthorizationTool.h文件

    #import <Foundation/Foundation.h>
    
    typedef NS_ENUM(NSUInteger, WTAuthorizationStatus) {
        WTAuthorizationStatusAuthorized = 0,    // 已授权
        WTAuthorizationStatusDenied,            // 拒绝
        WTAuthorizationStatusRestricted,        // 应用没有相关权限,且当前用户无法改变这个权限,比如:家长控制
        WTAuthorizationStatusNotSupport         // 硬件等不支持
    };
    
    @interface WTAuthorizationTool : NSObject
    
    /**
     *  请求相册访问权限
     *
     *  @param callback <#callback description#>
     */
    + (void)requestImagePickerAuthorization:(void(^)(WTAuthorizationStatus status))callback;
    
    /**
     *  请求相机权限
     *
     *  @param callback <#callback description#>
     */
    + (void)requestCameraAuthorization:(void(^)(WTAuthorizationStatus status))callback;
    
    + (void)requestAddressBookAuthorization:(void (^)(WTAuthorizationStatus))callback;
    
    @end
    

    WTAuthorizationTool.m文件

    #import "WTAuthorizationTool.h"
    
    #import <AssetsLibrary/AssetsLibrary.h>
    #import <Photos/Photos.h>
    #import <AddressBook/AddressBook.h>
    #import <AddressBookUI/AddressBookUI.h>
    #import <ContactsUI/ContactsUI.h>
    
    @implementation WTAuthorizationTool
    
    #pragma mark - 相册
    + (void)requestImagePickerAuthorization:(void(^)(WTAuthorizationStatus status))callback {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ||
            [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
            if (authStatus == ALAuthorizationStatusNotDetermined) { // 未授权
                if ([UIDevice currentDevice].systemVersion.floatValue < 8.0) {
                    [self executeCallback:callback status:WTAuthorizationStatusAuthorized];
                } else {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                        if (status == PHAuthorizationStatusAuthorized) {
                            [self executeCallback:callback status:WTAuthorizationStatusAuthorized];
                        } else if (status == PHAuthorizationStatusDenied) {
                            [self executeCallback:callback status:WTAuthorizationStatusDenied];
                        } else if (status == PHAuthorizationStatusRestricted) {
                            [self executeCallback:callback status:WTAuthorizationStatusRestricted];
                        }
                    }];
                }
                
            } else if (authStatus == ALAuthorizationStatusAuthorized) {
                [self executeCallback:callback status:WTAuthorizationStatusAuthorized];
            } else if (authStatus == ALAuthorizationStatusDenied) {
                [self executeCallback:callback status:WTAuthorizationStatusDenied];
            } else if (authStatus == ALAuthorizationStatusRestricted) {
                [self executeCallback:callback status:WTAuthorizationStatusRestricted];
            }
        } else {
            [self executeCallback:callback status:WTAuthorizationStatusNotSupport];
        }
    }
    
    #pragma mark - 相机
    + (void)requestCameraAuthorization:(void (^)(WTAuthorizationStatus))callback {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStatus == AVAuthorizationStatusNotDetermined) {
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {
                        [self executeCallback:callback status:WTAuthorizationStatusAuthorized];
                    } else {
                        [self executeCallback:callback status:WTAuthorizationStatusDenied];
                    }
                }];
            } else if (authStatus == AVAuthorizationStatusAuthorized) {
                [self executeCallback:callback status:WTAuthorizationStatusAuthorized];
            } else if (authStatus == AVAuthorizationStatusDenied) {
                [self executeCallback:callback status:WTAuthorizationStatusDenied];
            } else if (authStatus == AVAuthorizationStatusRestricted) {
                [self executeCallback:callback status:WTAuthorizationStatusRestricted];
            }
        } else {
            [self executeCallback:callback status:WTAuthorizationStatusNotSupport];
        }
    }
    
    #pragma mark - 通讯录
    + (void)requestAddressBookAuthorization:(void (^)(WTAuthorizationStatus))callback {
        ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
        if (authStatus == kABAuthorizationStatusNotDetermined) {
            __block ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
            if (addressBook == NULL) {
                [self executeCallback:callback status:WTAuthorizationStatusNotSupport];
                return;
            }
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                if (granted) {
                    [self executeCallback:callback status:WTAuthorizationStatusAuthorized];
                } else {
                    [self executeCallback:callback status:WTAuthorizationStatusDenied];
                }
                if (addressBook) {
                    CFRelease(addressBook);
                    addressBook = NULL;
                }
            });
            return;
        } else if (authStatus == kABAuthorizationStatusAuthorized) {
            [self executeCallback:callback status:WTAuthorizationStatusAuthorized];
        } else if (authStatus == kABAuthorizationStatusDenied) {
            [self executeCallback:callback status:WTAuthorizationStatusDenied];
        } else if (authStatus == kABAuthorizationStatusRestricted) {
            [self executeCallback:callback status:WTAuthorizationStatusRestricted];
        }
    }
    
    #pragma mark - callback
    + (void)executeCallback:(void (^)(WTAuthorizationStatus))callback status:(WTAuthorizationStatus)status {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (callback) {
                    callback(status);
            }
        });
    }
    
    @end
    
  • 界面测试提示

    controller部分代码

    - (void)requestAddressBook {
        [WTAuthorizationTool requestAddressBookAuthorization:^(WTAuthorizationStatus status) {
            [self requestAuthCallback:status];
        }];
    }
    
    - (void)requestCamera {
        [WTAuthorizationTool requestCameraAuthorization:^(WTAuthorizationStatus status) {
            [self requestAuthCallback:status];
        }];
    }
    
    - (void)requestAlbum {
        [WTAuthorizationTool requestImagePickerAuthorization:^(WTAuthorizationStatus status) {
            [self requestAuthCallback:status];
        }];
    }
    
    - (void)requestAuthCallback:(WTAuthorizationStatus)status {
        switch (status) {
            case WTAuthorizationStatusAuthorized:
                [WTAlert showAlertFrom:self title:@"授权成功" message:@"可以访问你要访问的内容了" cancelButtonTitle:@"我知道了" cancle:^{
                    
                } confirmButtonTitle:nil confirm:nil];
                break;
                
            case WTAuthorizationStatusDenied:
            case WTAuthorizationStatusRestricted:
                [WTAlert showAlertFrom:self title:@"授权失败" message:@"用户拒绝" cancelButtonTitle:@"我知道了" cancle:^{
                    
                } confirmButtonTitle:@"现在设置" confirm:^{
                    NSURL *settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:settingUrl]) {
                        [[UIApplication sharedApplication] openURL:settingUrl];
                    }
                }];
                break;
                
            case WTAuthorizationStatusNotSupport:
                [WTAlert showAlertFrom:self title:@"授权失败" message:@"设备不支持" cancelButtonTitle:@"我知道了" cancle:^{
                    
                } confirmButtonTitle:nil confirm:nil];
                
            default:
                break;
        }
    }
    

六、源码

完整源码

  • 使用WTAuthorizationTool

    pod "WTAuthorizationTool"
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,968评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,601评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,220评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,416评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,425评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,144评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,432评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,088评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,586评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,028评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,137评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,783评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,343评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,333评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,559评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,595评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,901评论 2 345

推荐阅读更多精彩内容