iOS 各种授权方法

1、iOS开发检测是否开启定位:

需要导入:

#import 

代码如下

+ (void)openLocationServiceWithBlock:(void(^)(BOOL))callback
{
  BOOL isOPen = NO;
  if ([CLLocationManager locationServicesEnabled] &&
      [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
    isOPen = YES;
  }
    callback(isOPen);
}

2、iOS开发检测是否允许消息推送:

需要导入:

#import 

代码如下

+ (void)openMessageNotificationServiceWithBlock:(void(^)(BOOL))callback
{
     BOOL isOpen = NO;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
     UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
     if (setting.types != UIUserNotificationTypeNone) {
       isOpen = YES;
     }
#else
     UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
     if (type != UIRemoteNotificationTypeNone) {
       isOpen = YES;
     }
#endif
    callback(isOpen);
}
+ (void)openMessageNotificationServiceWithBlock:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
 [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
     callback(settings.authorizationStatus == UNAuthorizationStatusAuthorized);
 }];
#elif __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
    callback([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]);
#else
    UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
    callback(type != UIRemoteNotificationTypeNone);
#endif
}

3、iOS开发检测是否开启摄像头:

需要导入:

#import 

代码如下:

+ (void)openCaptureDeviceServiceWithBlock:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
  AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  if (authStatus == AVAuthorizationStatusNotDetermined) {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        callback(granted);
    }];
  } else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
      callback(NO);
  } else {
      callback(YES);
  }
#endif
}

4、iOS开发检测是否开启相册:

需要导入:

#import 
#import 

代码如下:

+ (void)openAlbumServiceWithBlock:(void(^)(BOOL))callback
{
    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
    callback(isOpen);
}

5、iOS开发检测是否开启麦克风:

需要导入:

#import 

代码如下:

+ (void)openRecordServiceWithBlock:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
  AVAudioSessionRecordPermission permissionStatus = [[AVAudioSession sharedInstance] recordPermission];
  if (permissionStatus == AVAudioSessionRecordPermissionUndetermined) {
    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        callback(granted);
    }];
  } else if (permissionStatus == AVAudioSessionRecordPermissionDenied) {
      callback(NO);
  } else {
      callback(YES);
  }
#endif
}

6、iOS开发检测是否开启通讯录:

需要导入:

#import 
#import 

代码如下:

+ (void)openContactsServiceWithBolck:(void(^)(BOOL))callback
{
#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) {
      callback(granted);
  }];
 } else if (cnAuthStatus == CNAuthorizationStatusRestricted || cnAuthStatus == CNAuthorizationStatusDenied) {
     callback(NO);
 } else {
     callback(YES);
 }
#else
 //ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
 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) {
         callback(NO);
     }
    } else {
        callback(YES);
    }
   });
  });
 } else {
     callback(YES);
 }
#endif
}

7、iOS开发检测是否开启蓝牙:

需要导入:

#import 

代码如下:

+ (void)openPeripheralServiceWithBolck:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
  CBPeripheralManagerAuthorizationStatus cbAuthStatus = [CBPeripheralManager authorizationStatus];
  if (cbAuthStatus == CBPeripheralManagerAuthorizationStatusNotDetermined) {
      callback(NO);
  } else if (cbAuthStatus == CBPeripheralManagerAuthorizationStatusRestricted || cbAuthStatus == CBPeripheralManagerAuthorizationStatusDenied) {
      callback(NO);
  } else {
      callback(YES);
  }
#endif
}

8、iOS开发检测是否开启日历/备忘录:

需要导入:

#import 

代码如下:

+ (void)openEventServiceWithBolck:(void(^)(BOOL))callback withType:(EKEntityType)entityType
{
  // EKEntityTypeEvent  代表日历
  // EKEntityTypeReminder 代表备忘
  EKAuthorizationStatus ekAuthStatus = [EKEventStore authorizationStatusForEntityType:entityType];
  if (ekAuthStatus == EKAuthorizationStatusNotDetermined) {
    EKEventStore *store = [[EKEventStore alloc] init];
    [store requestAccessToEntityType:entityType completion:^(BOOL granted, NSError *error) {
        callback(granted);
    }];
  } else if (ekAuthStatus == EKAuthorizationStatusRestricted || ekAuthStatus == EKAuthorizationStatusDenied) {
      callback(NO);
  } else {
      callback(YES);
  }
}

9、iOS开发检测是否开启联网:

需要导入:

#import 

代码如下:

+ (void)openEventServiceWithBolck:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
  CTCellularData *cellularData = [[CTCellularData alloc] init];
  cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state){
    if (state == kCTCellularDataRestrictedStateUnknown || state == kCTCellularDataNotRestricted) {
        callback(NO);
    } else {
        callback(YES);
    }
  };
  CTCellularDataRestrictedState state = cellularData.restrictedState;
  if (state == kCTCellularDataRestrictedStateUnknown || state == kCTCellularDataNotRestricted) {
      callback(NO);
  } else {
      callback(YES);
  }
#endif
}

10、iOS开发检测是否开启健康:

需要导入:

#import 

代码如下:

+ (void)openHealthServiceWithBolck:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
 if (![HKHealthStore isHealthDataAvailable]) {
     callback(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  * 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  * 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) {
       callback(success);
   }];
  } else if (hkAuthStatus == HKAuthorizationStatusSharingDenied) {
      callback(NO);
  } else {
      callback(YES);
  }
 }
#endif
}

11、iOS开发检测是否开启Touch ID:

需要导入:

#import 

代码如下:

+ (void)openTouchIDServiceWithBlock:(void(^)(BOOL))callback
{
#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) {
    // 识别成功
       [[NSOperationQueue mainQueue] addOperationWithBlock:^{
           callback(YES);
       }];
   } else if (error) {
       [[NSOperationQueue mainQueue] addOperationWithBlock:^{
           callback(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);
     callback(NO);
 }
#endif
}

12、iOS开发检测是否开启Apple Pay:

需要导入:

#import 

代码如下:

+ (void)openApplePayServiceWithBlock:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0
  NSArray *supportedNetworks = @[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa, PKPaymentNetworkDiscover];
  if ([PKPaymentAuthorizationViewController canMakePayments] && [PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:supportedNetworks]) {
      callback(YES);
  } else {
      callback(NO);
  }
#endif
}

13、iOS开发检测是否开启语音识别:

需要导入:

#import 

代码如下:

+ (void)openSpeechServiceWithBlock:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
 SFSpeechRecognizerAuthorizationStatus speechAuthStatus = [SFSpeechRecognizer authorizationStatus];
 if (speechAuthStatus == SFSpeechRecognizerAuthorizationStatusNotDetermined) {
  [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
   if (status == SFSpeechRecognizerAuthorizationStatusAuthorized) {
    dispatch_async(dispatch_get_main_queue(), ^{
        callback(YES);
    });
   } else {
    dispatch_async(dispatch_get_main_queue(), ^{
        callback(NO);
    });
   }
  }];
 } else if (speechAuthStatus == SFSpeechRecognizerAuthorizationStatusAuthorized) {
     callback(YES);
 } else{
     callback(NO);
 }
#endif
}

14、iOS开发检测是否开启媒体资料库/Apple Music:

需要导入:

#import 

代码如下:

+ (void)openMediaPlayerServiceWithBlock:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_3
 MPMediaLibraryAuthorizationStatus authStatus = [MPMediaLibrary authorizationStatus];
 if (authStatus == MPMediaLibraryAuthorizationStatusNotDetermined) {
  [MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus status) {
   if (status == MPMediaLibraryAuthorizationStatusAuthorized) {
    dispatch_async(dispatch_get_main_queue(), ^{
        callback(YES);
    });
   }else{
    dispatch_async(dispatch_get_main_queue(), ^{
        callback(NO);
    });
   }
  }];
 }else if (authStatus == MPMediaLibraryAuthorizationStatusAuthorized){
     callback(YES);
 }else{
     callback(NO);
 }
#endif
}

15、iOS开发检测是否开启Siri:

需要导入:

#import 

代码如下:

+ (void)openSiriServiceWithBlock:(void(^)(BOOL))callback
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
 INSiriAuthorizationStatus siriAutoStatus = [INPreferences siriAuthorizationStatus];
 if (siriAutoStatus == INSiriAuthorizationStatusNotDetermined) {
  [INPreferences requestSiriAuthorization:^(INSiriAuthorizationStatus status) {
   if (status == INSiriAuthorizationStatusAuthorized) {
    dispatch_async(dispatch_get_main_queue(), ^{
        callback(YES);
    });
   } else {
    dispatch_async(dispatch_get_main_queue(), ^{
        callback(NO);
    });
   }
  }];
 } else if (siriAutoStatus == INSiriAuthorizationStatusAuthorized) {
     callback(YES);
 } else{
     callback(NO);
 }
#endif
}

由于iOS10的权限原因,需要在工程的info.plist(右击选择Open as - Source Code)中添加


NSPhotoLibraryUsageDescription 
App需要您的同意,才能访问相册 

NSCameraUsageDescription 
App需要您的同意,才能访问相机 

NSMicrophoneUsageDescription 
App需要您的同意,才能访问麦克风 

NSLocationUsageDescription 
App需要您的同意,才能访问位置 

NSLocationWhenInUseUsageDescription 
App需要您的同意,才能在使用期间访问位置 

NSLocationAlwaysUsageDescription 
App需要您的同意,才能始终访问位置 

NSCalendarsUsageDescription 
App需要您的同意,才能访问日历 

NSRemindersUsageDescription 
App需要您的同意,才能访问提醒事项 

NSMotionUsageDescription
 App需要您的同意,才能访问运动与健身 

NSHealthUpdateUsageDescription 
App需要您的同意,才能访问健康更新  

NSHealthShareUsageDescription 
App需要您的同意,才能访问健康分享 

NSBluetoothPeripheralUsageDescription 
App需要您的同意,才能访问蓝牙 

NSAppleMusicUsageDescription 
App需要您的同意,才能访问媒体资料库

NSSpeechRecognitionUsageDescription 
App需要您的同意,才能使用语音识别

https://blog.csdn.net/u012094456/article/details/111314100

你可能感兴趣的:(iOS 各种授权方法)