定位、通讯录、日历、提醒、照片、蓝牙、麦克风、相机、健康、Home、运动权限

iOS应用开发免不了使用设备硬件资源,这是都是要用授权的,授权路径在设置->隐私;

一、定位服务

1、获取授权状态

- (void)checkLocationServicesAuthorizationStatus {
    /*
     We can ask the location services manager ahead of time what the authorization status is for our bundle and take the appropriate action.
     */
    [self reportLocationServicesAuthorizationStatus:[CLLocationManager authorizationStatus]];
}

- (void)reportLocationServicesAuthorizationStatus:(CLAuthorizationStatus)status {
    NSString *statusText = nil;
    if(status == kCLAuthorizationStatusNotDetermined) {
        statusText = NSLocalizedString(@"UNDETERMINED", @"");
    }
    else if(status == kCLAuthorizationStatusRestricted) {
        statusText = NSLocalizedString(@"RESTRICTED", @"");
    }
    else if(status == kCLAuthorizationStatusDenied) {
        statusText = NSLocalizedString(@"DENIED", @"");
    }
    else if(status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        statusText = NSLocalizedString(@"LOCATION_WHEN_IN_USE", @"");
    }
    else if(status == kCLAuthorizationStatusAuthorizedAlways) {
        statusText = NSLocalizedString(@"LOCATION_ALWAYS", @"");
    }
    
    [self alertViewWithDataClass:Location status:statusText];
}
2、获取授权

- (void)requestLocationServicesAuthorization {
    if (!self.locationManager) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
    }
    
    /*
     Gets user permission to get their location while the app is in the foreground.
     
     To monitor the user's location even when the app is in the background:
     1. Replace [self.locationManager requestWhenInUseAuthorization] with [self.locationManager requestAlwaysAuthorization]
     2. Change NSLocationWhenInUseUsageDescription to NSLocationAlwaysUsageDescription in InfoPlist.strings
     */
    [self.locationManager requestWhenInUseAuthorization];
    
    /*
     Requests a single location after the user is presented with a consent dialog.
     */
    [self.locationManager startUpdatingLocation];
}

#pragma mark - CLLocationMangerDelegate methods

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    /*
     Handle the failure...
     */
    [self.locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    /*
     Do something with the new location the application just received...
     */
    [self.locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    /*
     The delegate function will be called when the permission status changes the application should then attempt to handle the change appropriately by changing UI or setting up or tearing down data structures.
     */
    [self reportLocationServicesAuthorizationStatus:status];
}


3、plist中添加key

 NSLocationWhenInUseUsageDescription 或者 NSLocationAlwaysUsageDescription


二、通讯录

1、获取授权状态

iOS8

    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    if(status == kABAuthorizationStatusNotDetermined) {
        [self alertViewWithMessage:NSLocalizedString(@"UNDETERMINED", @"")];
    }
    else if(status == kABAuthorizationStatusRestricted) {
        
        [self alertViewWithMessage:NSLocalizedString(@"RESTRICTED", @"")];
    }
    else if(status == kABAuthorizationStatusDenied) {
        
        [self alertViewWithMessage:NSLocalizedString(@"DENIED", @"")];
    }
    else if(status == kABAuthorizationStatusAuthorized) {
        [self alertViewWithMessage:NSLocalizedString(@"GRANTED", @"")];
    }


iOS9

- (void)checkContactStoreAccess {
    /*
     We can ask the contact store ahead of time what the authorization status is for our bundle and take the appropriate action.
     */
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if(status == CNAuthorizationStatusNotDetermined) {
        [self alertViewWithDataClass:Contacts status:NSLocalizedString(@"UNDETERMINED", @"")];
    }
    else if(status == CNAuthorizationStatusRestricted) {
        [self alertViewWithDataClass:Contacts status:NSLocalizedString(@"RESTRICTED", @"")];
    }
    else if(status == CNAuthorizationStatusDenied) {
        [self alertViewWithDataClass:Contacts status:NSLocalizedString(@"DENIED", @"")];
    }
    else if(status == CNAuthorizationStatusAuthorized) {
        [self alertViewWithDataClass:Contacts status:NSLocalizedString(@"GRANTED", @"")];
    }
}

2、获取授权

iOS8

- (void)requestAddressBookAccess {
    CFErrorRef myError = NULL;
    ABAddressBookRef myAddressBook = ABAddressBookCreateWithOptions(NULL, &myError);
    APLPrivacyClassesTableViewController * __weak weakSelf = self;  // avoid capturing self in the block
    ABAddressBookRequestAccessWithCompletion(myAddressBook,^(bool granted, CFErrorRef error){

        [weakSelf checkAddressBookAccess];
                                                 
         CFRelease(myAddressBook);
    });

}

iOS9

- (void)requestContactStoreAccess {
    if(!self.contactStore) {
        self.contactStore = [[CNContactStore alloc] init];
    }
    
    [self.contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self alertViewWithDataClass:Contacts status:(granted) ? NSLocalizedString(@"GRANTED", @"") : NSLocalizedString(@"DENIED", @"")];
            
            /*
             Do something with the access to the contact store...
             */
        });
    }];    
}


3、plist中添加key

NSContactsUsageDescription


三、日历

1、授权状态

 [self checkEventStoreAccessForType:EKEntityTypeEvent];
- (void)checkEventStoreAccessForType:(EKEntityType)type {
    /*
     We can ask the event store ahead of time what the authorization status is for our bundle and take the appropriate action.
     */
    EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:type];
    if(status == EKAuthorizationStatusNotDetermined) {
        [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:NSLocalizedString(@"UNDETERMINED", @"")];
    }
    else if(status == EKAuthorizationStatusRestricted) {
        [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:NSLocalizedString(@"RESTRICTED", @"")];
    }
    else if(status == EKAuthorizationStatusDenied) {
        [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:NSLocalizedString(@"DENIED", @"")];
    }
    else if(status == EKAuthorizationStatusAuthorized) {
        [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:NSLocalizedString(@"GRANTED", @"")];
    }
}

2、获取授权

            [self requestEventStoreAccessWithType:EKEntityTypeEvent];

- (void)requestEventStoreAccessWithType:(EKEntityType)type {
    if(!self.eventStore) {
        self.eventStore = [[EKEventStore alloc] init];
    }
    
    /*
     When the application requests to receive event store data that is when the user is presented with a consent dialog.
     */
    [self.eventStore requestAccessToEntityType:type completion:^(BOOL granted, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:(granted) ? NSLocalizedString(@"GRANTED", @"") : NSLocalizedString(@"DENIED", @"")];
            
            /*
             Do something with the access to eventstore...
             */
        });
    }];
}

3、plist中添加key

NSCalendarsUsageDescription


四、提醒事项

1、权限状态

            [self checkEventStoreAccessForType:EKEntityTypeReminder];

- (void)checkEventStoreAccessForType:(EKEntityType)type {
    /*
     We can ask the event store ahead of time what the authorization status is for our bundle and take the appropriate action.
     */
    EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:type];
    if(status == EKAuthorizationStatusNotDetermined) {
        [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:NSLocalizedString(@"UNDETERMINED", @"")];
    }
    else if(status == EKAuthorizationStatusRestricted) {
        [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:NSLocalizedString(@"RESTRICTED", @"")];
    }
    else if(status == EKAuthorizationStatusDenied) {
        [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:NSLocalizedString(@"DENIED", @"")];
    }
    else if(status == EKAuthorizationStatusAuthorized) {
        [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:NSLocalizedString(@"GRANTED", @"")];
    }
}

2、获取权限

            [self requestEventStoreAccessWithType:EKEntityTypeReminder];

- (void)requestEventStoreAccessWithType:(EKEntityType)type {
    if(!self.eventStore) {
        self.eventStore = [[EKEventStore alloc] init];
    }
    
    /*
     When the application requests to receive event store data that is when the user is presented with a consent dialog.
     */
    [self.eventStore requestAccessToEntityType:type completion:^(BOOL granted, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self alertViewWithDataClass:((type == EKEntityTypeEvent) ? Calendars : Reminders) status:(granted) ? NSLocalizedString(@"GRANTED", @"") : NSLocalizedString(@"DENIED", @"")];
            
            /*
             Do something with the access to eventstore...
             */
        });
    }];
}

3、plist中添加key

NSRemindersUsageDescription


五、照片

1、权限状态

- (void)reportPhotosAuthorizationStatus {
    /*
     We can ask the photo library ahead of time what the authorization status is for our bundle and take the appropriate action.
     */
    NSString *statusText = nil;
    if([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusNotDetermined) {
       statusText = NSLocalizedString(@"UNDETERMINED", @"");
    }
    else if([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusRestricted) {
        statusText = NSLocalizedString(@"RESTRICTED", @"");
    }
    else if([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusDenied) {
        statusText = NSLocalizedString(@"DENIED", @"");
    }
    else if([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
        statusText = NSLocalizedString(@"GRANTED", @"");
    }
    
    NSString *message = [NSString stringWithFormat:NSLocalizedString(@"PHOTOS_ACCESS_LEVEL", @""), statusText];
    [self alertViewWithMessage:message];
}

2、获取权限

- (void)requestPhotosAccessUsingImagePicker {
    /*
    There are two ways to prompt the user for permission to access photos. This one will display the photo picker UI.  See the PHPhotoLibrary example in this file for the other way to request photo access.
     */
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    
    /*
     Upon presenting the picker, consent will be required from the user if the user previously denied access to the photo library, an "access denied" lock screen will be presented to the user to remind them of this choice.
     */
    [self.navigationController presentViewController:picker animated:YES completion:nil];
}

- (void)requestPhotosAccessUsingPhotoLibrary {
    /*
     There are two ways to prompt the user for permission to access photos. This one will not display the photo picker UI.  See the UIImagePickerController example in this file for the other way to request photo access.
     */
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self reportPhotosAuthorizationStatus];
        });
    }];
}


3、plist中添加key


NSPhotoLibraryUsageDescription 

六、蓝牙共享

1、权限状态

- (void)checkBluetoothAccess {
    if(!self.cbManager) {
        self.cbManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    
    /*
     We can ask the bluetooth manager ahead of time what the authorization status is for our bundle and take the appropriate action.
     */
    CBCentralManagerState state = [self.cbManager state];
    if(state == CBCentralManagerStateUnknown) {
        [self alertViewWithDataClass:Bluetooth status:NSLocalizedString(@"UNKNOWN", @"")];
    }
    else if(state == CBCentralManagerStateUnauthorized) {
        [self alertViewWithDataClass:Bluetooth status:NSLocalizedString(@"DENIED", @"")];
    }
    else {
        [self alertViewWithDataClass:Bluetooth status:NSLocalizedString(@"GRANTED", @"")];
    }
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    /*
     The delegate method will be called when the permission status changes the application should then attempt to handle the change appropriately by changing UI or setting up or tearing down data structures.
     */
}

2、请求权限

- (void)requestBluetoothAccess {
    if(!self.cbManager) {
        self.cbManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    
    /*
     When the application requests to start scanning for bluetooth devices that is when the user is presented with a consent dialog.
     */
    [self.cbManager scanForPeripheralsWithServices:nil options:nil];
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    /*
     Handle the discovered bluetooth devices...
     */
}


3、plist中添加key

NSBluetoothPeripheralUsageDescription


七、麦克风

1、权限状态

官方暂无提供接口。

2、请求权限

- (void)requestMicrophoneAccess {
    AVAudioSession *session = [[AVAudioSession alloc] init];
    [session requestRecordPermission:^(BOOL granted) {
        if(granted) {
            NSError *error;
            /*
             Setting the category will also request access from the user
             */
            [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
            
            /*
             Do something with the audio session
             */
        }
        else {
            /*
             Handle failure
             */
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self alertViewWithDataClass:Microphone status:(granted) ? NSLocalizedString(@"GRANTED", @"") : NSLocalizedString(@"DENIED", @"")];
        });
    }];
}

3、plist中添加key

NSMicrophoneUsageDescription

八、相机

1、权限状态

- (void)checkCameraAccess {
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(status ==AVAuthorizationStatusNotDetermined) {
        [self alertViewWithMessage:NSLocalizedString(@"UNDETERMINED", @"")];
    }
    else if(status == AVAuthorizationStatusRestricted) {
        
        [self alertViewWithMessage:NSLocalizedString(@"RESTRICTED", @"")];
    }
    else if(status == AVAuthorizationStatusDenied) {
        
        [self alertViewWithMessage:NSLocalizedString(@"DENIED", @"")];
    }
    else if(status == AVAuthorizationStatusAuthorized) {
        [self alertViewWithMessage:NSLocalizedString(@"GRANTED", @"")];
    }
}


2、请求权限

- (void)requestCameraAccess {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        [self checkCameraAccess];
    }];
}


3、plist中添加key
NSCameraUsageDescription

九、健康

1、权限状态

- (void)checkHealthAccess {
    if ([HKHealthStore isHealthDataAvailable]) {
        if (!self.healthStore) {
            self.healthStore = [[HKHealthStore alloc] init];
        }
        
        HKQuantityType *heartRateType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
        HKAuthorizationStatus status = [self.healthStore authorizationStatusForType:heartRateType];
        
        if (status == HKAuthorizationStatusNotDetermined) {
            [self alertViewWithDataClass:Health status:NSLocalizedString(@"UNKNOWN", @"")];
        }
        else if (status == HKAuthorizationStatusSharingAuthorized) {
            [self alertViewWithDataClass:Health status:NSLocalizedString(@"GRANTED", @"")];
        }
        else if (status == HKAuthorizationStatusSharingDenied) {
            [self alertViewWithDataClass:Health status:NSLocalizedString(@"DENIED", @"")];
        }
    }
    else {
        // Health data is not available on all devices
        [self alertViewWithDataClass:Health status:NSLocalizedString(@"UNAVAILABLE", @"")];
    }
}


2、请求权限

- (void)requestHealthAccess {
    if ([HKHealthStore isHealthDataAvailable]) {
        if (!self.healthStore) {
            self.healthStore = [[HKHealthStore alloc] init];
        }
        
        HKQuantityType *heartRateType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
        NSSet *typeSet = [NSSet setWithObject:heartRateType];
        
        /*
         Requests consent from the user to read and write heart rate data from the health store
         */
        [self.healthStore requestAuthorizationToShareTypes:typeSet
                                                 readTypes:typeSet
                                                completion:^(BOOL success, NSError *error) {
                                                    dispatch_async(dispatch_get_main_queue(), ^{
                                                        [self checkHealthAccess];
                                                    });
                                                }];
    }
    else {
        // Health data is not available on all devices
        [self alertViewWithDataClass:Health status:NSLocalizedString(@"UNAVAILABLE", @"")];
    }
}


十、HomeKit

1、权限状态

官方暂无提供接口。

2、请求权限

- (void)requestHomeAccess {
    self.homeManager = [[HMHomeManager alloc] init];
    
    // HMHomeManager will notify the delegate when it's ready to vend home data. It will ask for user permission first, if needed.
    self.homeManager.delegate = self;
}

- (void)homeManagerDidUpdateHomes:(HMHomeManager *)manager {
    if (manager.homes.count > 0) {
        // A home exists, so we have access
        [self alertViewWithDataClass:Home status:NSLocalizedString(@"GRANTED", @"")];
    }
    else {
        // No homes are available.  Is that because no home is set in HMHomeManager, or because the user denied access?
        __weak HMHomeManager *weakHomeManager = manager; // Prevent memory leak
        [manager addHomeWithName:@"Test Home" completionHandler:^(HMHome *home, NSError *error) {
            
            if (!error) {
                [self alertViewWithDataClass:Home status:NSLocalizedString(@"GRANTED", @"")];
            }
            else {
                if (error.code == HMErrorCodeHomeAccessNotAuthorized) {
                    // User denied permission
                    [self alertViewWithDataClass:Home status:NSLocalizedString(@"DENIED", @"")];
                }
                else {
                    // Handle other errors cleanly
                    NSString *message = [NSString stringWithFormat:NSLocalizedString(@"HOME_ERROR", @""), error.code, error.localizedDescription];
                    [self alertViewWithMessage:message];
                }
            }
            
            if (home) {
                // Clean up after ourselves, don't leave the Test Home in the HMHomeManager array
                [weakHomeManager removeHome:home completionHandler:^(NSError * _Nullable error) {
                    // ... do something with the result of removing the home ...
                }];
            }
        }];
    }
}


十一、运动与健身

1、权限状态

官方暂无提供接口。

2、请求权限

- (void)requestMotionAccessData {
    self.cmManager = [[CMMotionActivityManager alloc] init];
    self.motionActivityQueue = [[NSOperationQueue alloc] init];
    [self.cmManager startActivityUpdatesToQueue:self.motionActivityQueue withHandler:^(CMMotionActivity *activity) {
        /* 
         * Do something with the activity reported
         */
        [self alertViewWithDataClass:Motion status:NSLocalizedString(@"ALLOWED", @"")];
        [self.cmManager stopActivityUpdates];
    }];
}

3、plist中添加key

NSMotionUsageDescription


官方Demo下载链接    官方Demo补充

阅读更多
版权声明:如果你觉得文章有用,请留言告诉我。 https://blog.csdn.net/ZWQ0325/article/details/51784049
文章标签: iOS 隐私 授权 定位
个人分类: iOS备忘录-原创
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭