判断的时候一定要写全4种情况
以Photos模块为例,所有的授权都分四种
- 授权未决定(弹出框的状态)NotDetermined
- 授权受限Restricted,当前不能接入,并不是未授权,可能是因为家长控制等等原因不能访问,很少见
- 授权拒绝Denied,就是用户拒绝了
- 授权接入Authorized
一般默认枚举的状态都是未决定.
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);
iOS7有什么大坑
iOS7应用被安装上的时候从未打开的时候,在”设置-隐私-相册”里是看不到app的授权状态的,甚至没有该app的图标.
所以说如果用以下代码判断,会出现一个大坑
- (BOOL)requestForPhotoAuthorization {
//创建一个信号
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
__block BOOL result = FALSE;
//
ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
switch (status) {
case ALAuthorizationStatusAuthorized:
result = TRUE;
break;
default:
break;
}
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
return result;
}
iOS7的情况下,还不能用Photos,用的是AssetLibrary,这里的大坑就是如果AssetLibrary如果没有探测到过ALAuthorizationStatusDenied,新应用在设置隐私里还是看不到app图标,此时程序通过requestForPhotoAuthorization去判断
- (void)tapGestureOnAlbumCell:(UITableViewCell *)cell {
if ([self requestForPhotoAuthorization]) {
//do something
}else {
[UIAlertView showWithMessage:@"请在 设置-隐私-照片 打开访问允许" delegate:nil];
}
}
由于requestForPhotoAuthorization始终返回的是FALSE,会收到提醒去开放权限的Alert,但是去设置里又看不到App,造成了死循环,始终无法访问相册.
这尼玛太坑了<(=┘ ̄Д ̄)┘╧═╧
如何解决大坑
见第一条!一定要把四种状态全部做判断
- (BOOL)requestForPhotoAuthorization {
//创建一个信号
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
__block BOOL result = FALSE;
//
ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
switch (status) {
case ALAuthorizationStatusAuthorized:
result = TRUE;
break;
case ALAuthorizationStatusRestricted:
break;
case ALAuthorizationStatusNotDetermined:
break;
case ALAuthorizationStatusDenied:
break;
default:
break;
}
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
return result;
}