#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h> // 定位
#import <UserNotifications/UserNotifications.h> // 推送
#import <AVFoundation/AVFoundation.h> // 摄像头 麦克风
#import <Photos/Photos.h> // 相册
#import <Contacts/Contacts.h> // 通讯录 9.0以后
#import <CoreBluetooth/CoreBluetooth.h> // 蓝牙
#import <EventKit/EventKit.h> // 日历和备忘录
#import <CoreTelephony/CTCellularData.h> // 蜂窝移动网
#import <HealthKit/HealthKit.h> // 健康
#import <LocalAuthentication/LocalAuthentication.h> // Touch ID
#import <PassKit/PassKit.h> // Apple Pay
#import <Speech/Speech.h> // 语音识别 10.0以后
#import <MediaPlayer/MediaPlayer.h> // 媒体资料库 9.3以后
#import <Intents/Intents.h> // Siri 10.0以后(其中某些内容更晚)
#if NS_BLOCKS_AVAILABLE
typedef void(^isOpenBlock)(BOOL isOpen);
#endif
@interface AuthorizationMgr : NSObject
/// 检测是否开启定位
+ (void)isLocationServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
/// 检测是否允许消息推送
+ (void)isMessageNotificationServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
/// 检测是否开启摄像头
//+ (void)isCaptureDeviceServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
/// 检测是否开启麦克风
//+ (void)isRecordServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
/// 检测是否开启相册
//+ (void)isAlbumServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
/// 检测是否开启通讯录
//+ (void)isContactsServiceOpenWithBolck:(isOpenBlock)returnBolck;
/// 检测是否开启蓝牙
//+ (void)isPeripheralServiceOpenWithBolck:(isOpenBlock)returnBolck;
/// 检测是否开启日历/备忘录
// EKEntityTypeEvent 代表日历
// EKEntityTypeReminder 代表备忘
//+ (void)isEventServiceOpenWithBolck:(isOpenBlock)returnBolck withType:(EKEntityType)entityType;
/// 检测是否开启蜂窝移动网络
+ (void)isCellularDataOpenWithBolck:(isOpenBlock)returnBolck;
/// 检测是否开启健康
//+ (void)isHealthServiceOpenWithBolck:(isOpenBlock)returnBolck;
/// 检测是否开启Touch ID
//+ (void)isTouchIDServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
/// 检测是否开启Apple Pay
//+ (void)isApplePayServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
/// 检测是否开启语音识别
//+ (void)isSpeechServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
/// 检测是否开启媒体资料库/Apple Music
//+ (void)isMediaPlayerServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
/// 检测是否开启Siri
//+ (void)isSiriServiceOpenWithBlock:(isOpenBlock)isOpenBlock;
@end
@implementation AuthorizationMgr
/// 检测是否开启定位
+ (void)isLocationServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
BOOL isOpen = NO;
if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
isOpen = YES;
}
if (isOpenBlock) {
isOpenBlock(isOpen);
}
}
/// 检测是否允许消息推送
+ (void)isMessageNotificationServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
BOOL isOpen = NO;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
if (@available(iOS 10.0, *)) {
[[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
if (isOpenBlock) {
isOpenBlock(settings.authorizationStatus == UNAuthorizationStatusAuthorized);
}
}];
} else {
// 8.0以后
UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
if (setting.types != UIUserNotificationTypeNone) {
isOpen = YES;
}
}
#else
// 8.0之前的
UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (type != UIRemoteNotificationTypeNone) {
isOpen = YES;
}
#endif
if (isOpenBlock) {
isOpenBlock(isOpen);
}
}
/// 检测是否开启摄像头
+ (void)isCaptureDeviceServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusNotDetermined) {
// 尚未拒绝或授权,提示授权
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if (isOpenBlock) {
isOpenBlock(granted);
}
}];
} else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
isOpenBlock(NO);
} else {
isOpenBlock(YES);
}
#endif
}
/// 检测是否开启麦克风
+ (void)isRecordServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
AVAudioSessionRecordPermission permissionStatus = [[AVAudioSession sharedInstance] recordPermission];
if (permissionStatus == AVAudioSessionRecordPermissionUndetermined) {
[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
if (isOpenBlock) {
isOpenBlock(granted);
}
}];
} else if (permissionStatus == AVAudioSessionRecordPermissionDenied) {
isOpenBlock(NO);
} else {
isOpenBlock(YES);
}
#endif
}
/// 检测是否开启相册
+ (void)isAlbumServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
BOOL isOpen;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
PHAuthorizationStatus authStatus = [PHPhotoLibrary authorizationStatus];
isOpen = YES;
if (authStatus == PHAuthorizationStatusRestricted || authStatus == PHAuthorizationStatusDenied) {
isOpen = NO;
}
#else
ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
isOpen = YES;
if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied) {
isOpen = NO;
}
#endif
if (isOpenBlock) {
isOpenBlock(isOpen);
}
}
/// 检测是否开启通讯录
+ (void)isContactsServiceOpenWithBolck:(isOpenBlock)returnBolck {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
CNAuthorizationStatus cnAuthStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
if (cnAuthStatus == CNAuthorizationStatusNotDetermined) {
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError *error) {
if (returnBolck) {
returnBolck(granted);
}
}];
} else if (cnAuthStatus == CNAuthorizationStatusRestricted || cnAuthStatus == CNAuthorizationStatusDenied) {
if (returnBolck) {
returnBolck(NO);
}
} else {
if (returnBolck) {
returnBolck(YES);
}
}
#else
ABAddressBookRef addressBook = ABAddressBookCreate();
ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
if (authStatus != kABAuthorizationStatusAuthorized) {
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(@"Error: %@", (__bridge NSError *)error);
if (returnBolck) {
returnBolck(NO);
}
} else {
if (returnBolck) {
returnBolck(YES);
}
}
});
});
} else {
if (returnBolck) {
returnBolck(YES);
}
}
#endif
}
/// 检测是否开启蓝牙
+ (void)isPeripheralServiceOpenWithBolck:(isOpenBlock)returnBolck {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
CBPeripheralManagerAuthorizationStatus cbAuthStatus = [CBPeripheralManager authorizationStatus];
if (cbAuthStatus == CBPeripheralManagerAuthorizationStatusNotDetermined) {
if (returnBolck) {
returnBolck(NO);
}
} else if (cbAuthStatus == CBPeripheralManagerAuthorizationStatusRestricted || cbAuthStatus == CBPeripheralManagerAuthorizationStatusDenied) {
if (returnBolck) {
returnBolck(NO);
}
} else {
if (returnBolck) {
returnBolck(YES);
}
}
#endif
}
/// 检测是否开启日历/备忘录
// EKEntityTypeEvent 代表日历
// EKEntityTypeReminder 代表备忘
+ (void)isEventServiceOpenWithBolck:(isOpenBlock)returnBolck withType:(EKEntityType)entityType {
EKAuthorizationStatus ekAuthStatus = [EKEventStore authorizationStatusForEntityType:entityType];
if (ekAuthStatus == EKAuthorizationStatusNotDetermined) {
EKEventStore *store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:entityType completion:^(BOOL granted, NSError *error) {
if (returnBolck) {
returnBolck(granted);
}
}];
} else if (ekAuthStatus == EKAuthorizationStatusRestricted || ekAuthStatus == EKAuthorizationStatusDenied) {
if (returnBolck) {
returnBolck(NO);
}
} else {
if (returnBolck) {
returnBolck(YES);
}
}
}
/// 检测是否开启蜂窝移动网络
+ (void)isCellularDataOpenWithBolck:(isOpenBlock)returnBolck {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
CTCellularData *cellularData = [[CTCellularData alloc] init];
cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state){
if (state == kCTCellularDataRestrictedStateUnknown || state == kCTCellularDataRestricted) {
if (returnBolck) {
returnBolck(NO);
}
} else {
if (returnBolck) {
returnBolck(YES);
}
}
};
#endif
}
/// 检测是否开启健康
+ (void)isHealthServiceOpenWithBolck:(isOpenBlock)returnBolck {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
if (![HKHealthStore isHealthDataAvailable]) {
if (returnBolck) {
returnBolck(NO);
}
} else {
HKHealthStore *healthStore = [[HKHealthStore alloc] init];
HKObjectType *hkObjectType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight];
HKAuthorizationStatus hkAuthStatus = [healthStore authorizationStatusForType:hkObjectType];
if (hkAuthStatus == HKAuthorizationStatusNotDetermined) {
// 1. 你创建了一个NSSet对象,里面存有本篇教程中你将需要用到的从Health Stroe中读取的所有的类型:个人特征(血液类型、性别、出生日期)、数据采样信息(身体质量、身高)以及锻炼与健身的信息。
NSSet <HKObjectType *> * healthKitTypesToRead = [[NSSet alloc] initWithArray:@[[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth],[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBloodType],[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight],[HKObjectType workoutType]]];
// 2. 你创建了另一个NSSet对象,里面有你需要向Store写入的信息的所有类型(锻炼与健身的信息、BMI、能量消耗、运动距离)
NSSet <HKSampleType *> * healthKitTypesToWrite = [[NSSet alloc] initWithArray:@[[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex],[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierActiveEnergyBurned],[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning],[HKObjectType workoutType]]];
[healthStore requestAuthorizationToShareTypes:healthKitTypesToWrite readTypes:healthKitTypesToRead completion:^(BOOL success, NSError *error) {
if (returnBolck) {
returnBolck(success);
}
}];
} else if (hkAuthStatus == HKAuthorizationStatusSharingDenied) {
if (returnBolck) {
returnBolck(NO);
}
} else {
if (returnBolck) {
returnBolck(YES);
}
}
}
#endif
}
/// 检测是否开启Touch ID
+ (void)isTouchIDServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
LAContext *laContext = [[LAContext alloc] init];
laContext.localizedFallbackTitle = @"输入密码";
NSError *error;
if ([laContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
NSLog(@"恭喜,Touch ID可以使用!");
[laContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"需要验证您的指纹来确认您的身份信息" reply:^(BOOL success, NSError *error) {
if (success) {
// 识别成功
if (isOpenBlock) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
isOpenBlock(YES);
}];
}
} else if (error) {
if (isOpenBlock) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
isOpenBlock(NO);
}];
}
if (error.code == LAErrorAuthenticationFailed) {
// 验证失败
}
if (error.code == LAErrorUserCancel) {
// 用户取消
}
if (error.code == LAErrorUserFallback) {
// 用户选择输入密码
}
if (error.code == LAErrorSystemCancel) {
// 系统取消
}
if (error.code == LAErrorPasscodeNotSet) {
// 密码没有设置
}
}
}];
} else {
NSLog(@"设备不支持Touch ID功能,原因:%@",error);
if (isOpenBlock) {
isOpenBlock(NO);
}
}
#endif
}
/// 检测是否开启Apple Pay
+ (void)isApplePayServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
NSArray<PKPaymentNetwork> *supportedNetworks = @[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa, PKPaymentNetworkDiscover];
if ([PKPaymentAuthorizationViewController canMakePayments] && [PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:supportedNetworks]) {
if (isOpenBlock) {
isOpenBlock(YES);
}
} else {
if (isOpenBlock) {
isOpenBlock(NO);
}
}
#endif
}
/// 检测是否开启语音识别
+ (void)isSpeechServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
if (@available(iOS 10.0, *)) {
SFSpeechRecognizerAuthorizationStatus speechAuthStatus = [SFSpeechRecognizer authorizationStatus];
if (speechAuthStatus == SFSpeechRecognizerAuthorizationStatusNotDetermined) {
[SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
if (status == SFSpeechRecognizerAuthorizationStatusAuthorized) {
dispatch_async(dispatch_get_main_queue(), ^{
if (isOpenBlock) {
isOpenBlock(YES);
}
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
if (isOpenBlock) {
isOpenBlock(YES);
}
});
}
}];
} else if (speechAuthStatus == SFSpeechRecognizerAuthorizationStatusAuthorized) {
if (isOpenBlock) {
isOpenBlock(YES);
}
} else{
if (isOpenBlock) {
isOpenBlock(NO);
}
}
} else {
//iOS 10以前没有Speech
}
}
/// 检测是否开启媒体资料库/Apple Music
+ (void)isMediaPlayerServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
if (@available(iOS 9.3, *)) {
MPMediaLibraryAuthorizationStatus authStatus = [MPMediaLibrary authorizationStatus];
if (authStatus == MPMediaLibraryAuthorizationStatusNotDetermined) {
[MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus status) {
if (status == MPMediaLibraryAuthorizationStatusAuthorized) {
dispatch_async(dispatch_get_main_queue(), ^{
if (isOpenBlock) {
isOpenBlock(YES);
}
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
if (isOpenBlock) {
isOpenBlock(NO);
}
});
}
}];
}else if (authStatus == MPMediaLibraryAuthorizationStatusAuthorized){
if (isOpenBlock) {
isOpenBlock(YES);
}
}else{
if (isOpenBlock) {
isOpenBlock(NO);
}
}
} else {
//9.3以前不能读取媒体资料库
}
}
/// 检测是否开启Siri
+ (void)isSiriServiceOpenWithBlock:(isOpenBlock)isOpenBlock {
if (@available(iOS 10.0, *)) {
INSiriAuthorizationStatus siriAutoStatus = [INPreferences siriAuthorizationStatus];
if (siriAutoStatus == INSiriAuthorizationStatusNotDetermined) {
[INPreferences requestSiriAuthorization:^(INSiriAuthorizationStatus status) {
if (status == INSiriAuthorizationStatusAuthorized) {
dispatch_async(dispatch_get_main_queue(), ^{
if (isOpenBlock) {
isOpenBlock(YES);
}
});
} else {
dispatch_async(dispatch_get_main_queue(), ^{
if (isOpenBlock) {
isOpenBlock(YES);
}
});
}
}];
} else if (siriAutoStatus == INSiriAuthorizationStatusAuthorized) {
if (isOpenBlock) {
isOpenBlock(YES);
}
} else{
if (isOpenBlock) {
isOpenBlock(NO);
}
}
} else {
//iOS 10以前不能使用Siri
}
}
/*
需要在工程的info.plist(右击选择Open as - Source Code)中添加
<!-- 相册 -->
<key>NSPhotoLibraryUsageDescription</key>
<string>App需要您的同意,才能访问相册</string>
<!-- 相机 -->
<key>NSCameraUsageDescription</key>
<string>App需要您的同意,才能访问相机</string>
<!-- 麦克风 -->
<key>NSMicrophoneUsageDescription</key>
<string>App需要您的同意,才能访问麦克风</string>
<!-- 位置 -->
<key>NSLocationUsageDescription</key>
<string>App需要您的同意,才能访问位置</string>
<!-- 在使用期间访问位置 -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>App需要您的同意,才能在使用期间访问位置</string>
<!-- 始终访问位置 -->
<key>NSLocationAlwaysUsageDescription</key>
<string>App需要您的同意,才能始终访问位置</string>
<!-- 日历 -->
<key>NSCalendarsUsageDescription</key>
<string>App需要您的同意,才能访问日历</string>
<!-- 提醒事项 -->
<key>NSRemindersUsageDescription</key>
<string>App需要您的同意,才能访问提醒事项</string>
<!-- 运动与健身 -->
<key>NSMotionUsageDescription</key>
<string>App需要您的同意,才能访问运动与健身</string>
<!-- 健康更新 -->
<key>NSHealthUpdateUsageDescription</key>
<string>App需要您的同意,才能访问健康更新 </string>
<!-- 健康分享 -->
<key>NSHealthShareUsageDescription</key>
<string>App需要您的同意,才能访问健康分享</string>
<!-- 蓝牙 -->
<key>NSBluetoothPeripheralUsageDescription</key>
<string>App需要您的同意,才能访问蓝牙</string>
<!-- 媒体资料库 -->
<key>NSAppleMusicUsageDescription</key>
<string>App需要您的同意,才能访问媒体资料库</string>
<!-- 语音识别 -->
<key>NSSpeechRecognitionUsageDescription</key>
<string>App需要您的同意,才能使用语音识别</string>
*/
@end
网友评论