下面以获取系统相册权限为例,说明该工具的使用方法:
1.创建按钮
在控制器中拉输出口:
/** 相册按钮 */
@property (weak, nonatomic) IBOutlet UIButton *photoBtn;
按钮点击:
/** 获取相册权限 */
- (IBAction)getPhotoAuth:(UIButton *)sender {
// 检测当前应用是否获取相册权限
BOOL photoAuth = [GKAuthorizationTool checkAuthorizationWithType:GKAuthorizationTypePhoto];
if (photoAuth) { // 已经授权
sender.selected = YES;
}else{ // 未授权
sender.selected = NO;
// 开始授权
GKAuthorizationStatus status = [GKAuthorizationTool getPhotoAuthorizationStatus];
if (status == GKAuthorizationStatusNotDetermined) { // 未授权过
[GKAuthorizationTool requestPhotoAuthorizationCallback:^(GKAuthorizationStatus status) {
[self changeBtn:sender status:status];
}];
}else{ // 已授权过,后又关闭权限,直接跳转到系统设置中该应用的授权界面
[self openSettingURL];
}
}
}
改变按钮状态
// 改变按钮状态
- (void)changeBtn:(UIButton *)btn status:(GKAuthorizationStatus)status
{
switch (status) {
case GKAuthorizationStatusAuthorized: // 允许访问
btn.selected = YES;
break;
case GKAuthorizationStatusDenied:
case GKAuthorizationStatusRestricted: // 拒绝访问
{
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"用户拒绝授权" preferredStyle:UIAlertControllerStyleAlert];
[alertVC addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alertVC animated:YES completion:nil];
}
break;
case GKAuthorizationStatusNotSupport: // 不支持
{
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备不支持" preferredStyle:UIAlertControllerStyleAlert];
[alertVC addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alertVC animated:YES completion:nil];
}
break;
default:
break;
}
}
打开系统设置
/**
* 打开系统设置中对应应用的授权页面
*/
- (void)openSettingURL
{
NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:settingURL]) {
[[UIApplication sharedApplication] openURL:settingURL];
}
}
允许效果截图
至此,用户获取相册权限功能已全部完成。
该工具的github地址:GKAuthorizationTool