因?yàn)橄鄼C(jī)是相冊(cè)是日常開發(fā)中必不可少的功能,但是因?yàn)樘O果的隱私政策,每次訪問的時(shí)候都需要授權(quán),沒有授權(quán)app是無法訪問相冊(cè)和相機(jī)功能的,這樣會(huì)造成app在用戶第一次使用的時(shí)候出現(xiàn)一下顯示不正常或者沒有響應(yīng)的感覺。
為了能提高用戶的體驗(yàn)度,寫一下相機(jī)相冊(cè)簡(jiǎn)單的權(quán)限邏輯判斷。
1、相冊(cè)權(quán)限:
蘋果文檔中,相冊(cè)權(quán)限狀態(tài)有一下情況:
iOS 8.0+
API_AVAILABLE_BEGIN(macos(10.13), ios(8), tvos(10))
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 //已同意授權(quán) User has authorized this application to access photos data.
};
通過一下方法判斷是否繼續(xù)下一步
需要導(dǎo)入#import <Photos/Photos.h>
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusRestricted ||
status == PHAuthorizationStatusDenied)
{
//無權(quán)限
[SVProgressHUD showErrorWithStatus:@"Please set the Allow APP to access your photo album. Settings > Privacy > Album"];
return ;
}
//第一次進(jìn)來還沒有選擇是否授權(quán)
else if (status == PHAuthorizationStatusNotDetermined)
{
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
dispatch_async(dispatch_get_main_queue(), ^{
if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied)
{
// 用戶拒絕,跳轉(zhuǎn)到自定義提示頁面
}
else if (status == PHAuthorizationStatusAuthorized)
{
// 用戶授權(quán),彈出相冊(cè)對(duì)話框
}
});
}];
return;
}
else{
// 用戶授權(quán),彈出相冊(cè)對(duì)話框
}
2、相機(jī)
同相冊(cè)一樣,相機(jī)也是有對(duì)應(yīng)的權(quán)限狀態(tài)
typedef NS_ENUM(NSInteger, AVAuthorizationStatus) {
AVAuthorizationStatusNotDetermined = 0,//沒有選擇
AVAuthorizationStatusRestricted = 1,//已拒絕
AVAuthorizationStatusDenied = 2,//已拒絕
AVAuthorizationStatusAuthorized = 3,//已授權(quán)
} API_AVAILABLE(macos(10.14), ios(7.0)) __WATCHOS_PROHIBITED __TVOS_PROHIBITED;
導(dǎo)入#import <AVFoundation/AVCaptureDevice.h>
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
//無權(quán)限
return ;
}
else if (authStatus == AVAuthorizationStatusNotDetermined)
{
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if (!granted) {//不允許
}else{//開啟
}
}];
return;
}
else
{
//已授權(quán)
}
獲取麥克風(fēng)權(quán)限邏輯和相機(jī)是差不多的只需把AVMediaTypeVideo 替換成AVMediaTypeAudio就可以了。
這就是目前相機(jī)、相冊(cè)和麥克風(fēng)的權(quán)限邏輯了,需要注意的一點(diǎn)是,這些方法大多是異步的,所以如果要在返回后做對(duì)應(yīng)的操作,最好切換到主線程。