美文网首页iOS
iOS Kingdom — 权限手动请求

iOS Kingdom — 权限手动请求

作者: iOSKingdom | 来源:发表于2017-03-14 08:38 被阅读0次
    Dog
    从 iOS10 开始,权限请求开始变成了开发者的又一道门槛,很多开发者在不申请权限的情况下调用 API,这会使 APP 彻底 Crash。接下来,我将附上一部分的权限手动请求代码,帮你快速申请权限。

    1、相机权限

    #import <AVFoundation/AVFoundation.h>
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo
                                 completionHandler:^(BOOL granted) {
                                     NSError *error;
                                     if (granted) {
    //                                     WQLogMes(@"开启成功");
                                     }else {
    //                                     WQLogErr(@"开启失败");
                                     }
                                 }];
    

    2、位置权限

    位置权限请求有点特殊,如果你的 CLLocationManager 对象是在方法内的局部变量,这时你调用权限申请时,会出现权限请求提示框一闪而逝。而解决这个 Bug 的方法就是将局部变量改成全局变量。

    2.1 始终定位

    在 info.plist 中须加入 NSLocationAlwaysUsageDescription
    #import <CoreLocation/CoreLocation.h>
    // self.manager 是一个 CLLocationManager 的全局属性
    if (!self.manager) {
            self.manager = [[CLLocationManager alloc] init];
            self.manager.delegate = self;
        }
        [self.manager requestAlwaysAuthorization];
    

    2.2 使用期间定位

    在 info.plist 中须加入 NSLocationWhenInUseUsageDescription
    #import <CoreLocation/CoreLocation.h>
    // self.manager 是一个 CLLocationManager 的全局属性
    if (!self.manager) {
            self.manager = [[CLLocationManager alloc] init];
            self.manager.delegate = self;
        }
        [self.manager requestWhenInUseAuthorization];
    
    指定 CLLocationManager 对象的 CLLocationManagerDelegate 代理,当发生授权变更,将会调用 - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status 方法。

    3、日历权限

    #import <EventKit/EventKit.h>
    EKEventStore *store = [[EKEventStore alloc] init];
        [store requestAccessToEntityType:EKEntityTypeEvent
                              completion:^(BOOL granted,
                                           NSError * _Nullable error) {
                                  if (error) {
    //                                  WQLogErr(@"error: %@",error);
                                  }else {
                                      if (granted) {
    //                                      WQLogMes(@"请求成功");
                                      }else {
    //                                      WQLogErr(@"请求失败");
                                      }
                                  }
                              }];
    

    4、提醒事项

    #import <EventKit/EventKit.h>
    EKEventStore *store = [[EKEventStore alloc] init];
        [store requestAccessToEntityType:EKEntityTypeReminder
                              completion:^(BOOL granted,
                                           NSError * _Nullable error) {
                                  if (error) {
    //                                  WQLogErr(@"error: %@",error);
                                  }else {
                                      if (granted) {
    //                                      WQLogMes(@"请求成功");
                                      }else {
    //                                      WQLogErr(@"请求失败");
                                      }
                                  }
                              }];
    

    5、相册

    #import <Photos/Photos.h>
        if ([[UIDevice currentDevice].systemVersion floatValue] > 8.0) {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status == PHAuthorizationStatusAuthorized) {
    //                WQLogMes(@"授权成功");
                }else {
    //                WQLogErr(@"授权失败");
                }
            }];
        }
    

    6、通知

        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:
                                               UIUserNotificationTypeSound |
                                               UIUserNotificationTypeAlert |
                                               UIUserNotificationTypeBadge
                                                                                categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    

    7、麦克风

    #import <AVFoundation/AVFoundation.h>
    AVAudioSession *session = [AVAudioSession sharedInstance];
        [session requestRecordPermission:^(BOOL granted) {
            if (granted) {
    //            WQLogMes(@"请求成功");
            }else {
    //            WQLogErr(@"请求失败");
            }
        }];
    

    8、健康(Health)

    if (![HKHealthStore isHealthDataAvailable]) {
    //        WQLogErr(@"不支持 Health");
            return;
        }
        HKHealthStore *healthStore = [[HKHealthStore alloc] init];
        // Share body mass, height and body mass index
        NSSet *shareObjectTypes = [NSSet setWithObjects:
                                   [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],
                                   [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight],
                                   [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex],
                                   nil];
        // Read date of birth, biological sex and step count
        NSSet *readObjectTypes  = [NSSet setWithObjects:
                                   [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth],
                                   [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
                                   [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
                                   nil];
        [healthStore requestAuthorizationToShareTypes:shareObjectTypes
                                            readTypes:readObjectTypes
                                           completion:^(BOOL success,
                                                        NSError *error) {
                                               if (error) {
    //                                               WQLogErr(@"error: %@",error);
                                               }else {
                                                   if(success == YES){
    //                                                   WQLogMes(@"请求成功");
                                                   }
                                                   else{
    //                                                   WQLogErr(@"请求失败");
                                                   }
                                               }
                                           }];
    

    9、通讯录

        if ([[[UIDevice currentDevice] systemVersion] floatValue] > 9.0) {
            CNContactStore *store = [[CNContactStore alloc] init];
            [store requestAccessForEntityType:CNEntityTypeContacts
                            completionHandler:^(BOOL granted,
                                                NSError * _Nullable error) {
                                if (error) {
    //                                WQLogErr(@"error: %@",error);
                                }else {
                                    if (granted) {
    //                                    WQLogMes(@"请求成功");
                                    }else {
    //                                    WQLogErr(@"请求失败");
                                    }
                                }
                            }];
        }else {
            ABAddressBookRef addressBook = ABAddressBookCreate();
            ABAddressBookRequestAccessWithCompletion(addressBook,
                                                     ^(bool granted,
                                                       CFErrorRef error) {
                                                         if (error) {
    //                                                         WQLogErr(@"error: %@",error);
                                                         }else {
                                                             if (granted) {
    //                                                             WQLogMes(@"请求成功");
                                                             }else {
    //                                                             WQLogErr(@"请求失败");
                                                             }
                                                         }
                                                     });
        }
    
    GitHub 示例: https://github.com/AppleDP/WQPermissionRequest
    权限判定: http://www.jianshu.com/p/4d72b82301e1

    相关文章

      网友评论

        本文标题:iOS Kingdom — 权限手动请求

        本文链接:https://www.haomeiwen.com/subject/emuswttx.html