一、为什么要获取权限
在越来越注重个人隐私的今天,用户很多情况下希望自己能完全掌握自己手机应用对媒体信息的一些访问权限,比如相册、相机、通讯录等。苹果在iOS7、iOS8等几个系统版本对一些权限的控制都做了加强,需要用户授权后应用才有相关的访问权限。
场景:
-
在你获取相册数据的时候,如果用户拒绝授权,那么可能会获取不到数据,此时需要给用户相应的提示,告知用户是权限的问题,此时,就需要得知相应的权限状态给用户恰当的提示。
-
用户的设备没有相机输入设备,如果你想访问用户的相机,此时就需要判断用户设备是否支持,给出恰当的提示。
二、权限状态说明
-
相册、相机、通讯录等授权状态目前都有种,都可以对应以下几种状态:
AuthorizationStatusNotDetermined // 用户从未进行过授权等处理,首次访问相应内容会提示用户进行授权 AuthorizationStatusAuthorized = 0, // 用户已授权,允许访问 AuthorizationStatusDenied, // 用户拒绝访问 AuthorizationStatusRestricted, // 应用没有相关权限,且当前用户无法改变这个权限,比如:家长控制
三、权限获取
- 相册权限
-
是否支持
``` [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