您好,登錄后才能下訂單哦!
這篇文章主要介紹了iOS開發(fā)中如何檢測是否開啟定位、是否允許消息推送等權限,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
1.iOS開發(fā)檢測是否開啟定位:
需要導入:
#import <CoreLocation/CoreLocation.h>
代碼如下:
+ (void)openLocationServiceWithBlock:(ReturnBlock)returnBlock { BOOL isOPen = NO; if ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) { isOPen = YES; } if (returnBlock) { returnBlock(isOpen); } }
2.iOS開發(fā)檢測是否允許消息推送:
需要導入:
#import <UserNotifications/UserNotifications.h>
代碼如下:
+ (void)openMessageNotificationServiceWithBlock:(ReturnBlock)returnBlock { 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 if (returnBlock) { returnBlock(isOpen); } }
+ (void)openMessageNotificationServiceWithBlock:(ReturnBlock)returnBlock { #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) { if (returnBlock) { returnBlock(settings.authorizationStatus == UNAuthorizationStatusAuthorized); } }]; #elif __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0 returnBlock([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]); #else UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes]; if (returnBlock) { returnBlock(type != UIRemoteNotificationTypeNone); } #endif }
3.iOS開發(fā)檢測是否開啟攝像頭:
需要導入:
#import <AVFoundation/AVFoundation.h>
代碼如下:
+ (void)openCaptureDeviceServiceWithBlock:(ReturnBlock)returnBlock { #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0 AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; if (authStatus == AVAuthorizationStatusNotDetermined) { [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) { if (returnBlock) { returnBlock(granted); } }]; return NO; } else if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) { returnBlock(NO); } else { returnBlock(YES); } #endif }
4.iOS開發(fā)檢測是否開啟相冊:
需要導入:
#import <Photos/Photos.h>#import <AssetsLibrary/AssetsLibrary.h>
代碼如下:
+ (void)openAlbumServiceWithBlock:(ReturnBlock)returnBlock { 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 (returnBlock) { returnBlock(isOpen); } }
5.iOS開發(fā)檢測是否開啟麥克風:
需要導入:
#import <AVFoundation/AVFoundation.h>
代碼如下:
+ (void)openRecordServiceWithBlock:(ReturnBlock)returnBlock { #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0 AVAudioSessionRecordPermission permissionStatus = [[AVAudioSession sharedInstance] recordPermission]; if (permissionStatus == AVAudioSessionRecordPermissionUndetermined) { [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) { if (returnBlock) { returnBlock(granted); } }]; } else if (permissionStatus == AVAudioSessionRecordPermissionDenied) { returnBlock(NO); } else { returnBlock(YES); } #endif }
6.iOS開發(fā)檢測是否開啟通訊錄:
需要導入:
#import <AddressBook/AddressBook.h>#import <Contacts/Contacts.h>
代碼如下:
+ (void)openContactsServiceWithBolck:(ReturnBlock)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 = 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) { returnBolck(NO); } } else { if (returnBolck) { returnBolck(YES); } } }); }); } else { if (returnBolck) { returnBolck(YES); } } #endif }
7.iOS開發(fā)檢測是否開啟藍牙:
需要導入:
#import <CoreBluetooth/CoreBluetooth.h>
代碼如下:
+ (void)openPeripheralServiceWithBolck:(ReturnBlock)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 }
8.iOS開發(fā)檢測是否開啟日歷/備忘錄:
需要導入:
#import <EventKit/EventKit.h>
代碼如下:
+ (void)openEventServiceWithBolck:(ReturnBlock)returnBolck 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) { if (returnBolck) { returnBolck(granted); } }]; } else if (ekAuthStatus == EKAuthorizationStatusRestricted || ekAuthStatus == EKAuthorizationStatusDenied) { if (returnBolck) { returnBolck(NO); } } else { if (returnBolck) { returnBolck(YES); } } }
9.iOS開發(fā)檢測是否開啟聯(lián)網(wǎng):
需要導入:
#import <CoreTelephony/CTCellularData.h>
代碼如下:
+ (void)openEventServiceWithBolck:(ReturnBlock)returnBolck { #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0 CTCellularData *cellularData = [[CTCellularData alloc] init]; cellularData.cellularDataRestrictionDidUpdateNotifier = ^(CTCellularDataRestrictedState state){ if (state == kCTCellularDataRestrictedStateUnknown || state == kCTCellularDataNotRestricted) { if (returnBolck) { returnBolck(NO); } } else { if (returnBolck) { returnBolck(YES); } } }; CTCellularDataRestrictedState state = cellularData.restrictedState; if (state == kCTCellularDataRestrictedStateUnknown || state == kCTCellularDataNotRestricted) { if (returnBolck) { returnBolck(NO); } } else { if (returnBolck) { returnBolck(YES); } } #endif }
10.iOS開發(fā)檢測是否開啟健康:
需要導入:
#import <HealthKit/HealthKit.h>
代碼如下:
+ (void)openHealthServiceWithBolck:(ReturnBlock)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. 你創(chuàng)建了一個NSSet對象,里面存有本篇教程中你將需要用到的從Health Stroe中讀取的所有的類型:個人特征(血液類型、性別、出生日期)、數(shù)據(jù)采樣信息(身體質量、身高)以及鍛煉與健身的信息。 NSSet <HKObjectType *> * healthKitTypesToRead = [[NSSet alloc] initWithArray:@[[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth],[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBloodType],[HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight],[HKObjectType workoutType]]]; // 2. 你創(chuàng)建了另一個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 }
11.iOS開發(fā)檢測是否開啟Touch ID:
需要導入:
#import <LocalAuthentication/LocalAuthentication.h>
代碼如下:
#pragma mark - 開啟Touch ID服務 + (void)openTouchIDServiceWithBlock:(ReturnBlock)returnBlock { #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 (returnBlock) { [[NSOperationQueue mainQueue] addOperationWithBlock:^{ returnBlock(YES); }]; } } else if (error) { if (returnBlock) { [[NSOperationQueue mainQueue] addOperationWithBlock:^{ returnBlock(NO); }]; } if (error.code == LAErrorAuthenticationFailed) { // 驗證失敗 } if (error.code == LAErrorUserCancel) { // 用戶取消 } if (error.code == LAErrorUserFallback) { // 用戶選擇輸入密碼 } if (error.code == LAErrorSystemCancel) { // 系統(tǒng)取消 } if (error.code == LAErrorPasscodeNotSet) { // 密碼沒有設置 } } }]; } else { NSLog(@"設備不支持Touch ID功能,原因:%@",error); if (returnBlock) { returnBlock(NO); } } #endif }
12.iOS開發(fā)檢測是否開啟Apple Pay:
需要導入:
#import <PassKit/PassKit.h>
代碼如下:
#pragma mark - 開啟Apple Pay服務 + (void)openApplePayServiceWithBlock:(ReturnBlock)returnBlock { #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0 NSArray<PKPaymentNetwork> *supportedNetworks = @[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa, PKPaymentNetworkDiscover]; if ([PKPaymentAuthorizationViewController canMakePayments] && [PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:supportedNetworks]) { if (returnBlock) { returnBlock(YES); } } else { if (returnBlock) { returnBlock(NO); } } #endif }
13.iOS開發(fā)檢測是否開啟語音識別:
需要導入:
#import <Speech/Speech.h>
代碼如下:
#pragma mark - 開啟語音識別服務 + (void)openSpeechServiceWithBlock:(ReturnBlock)returnBlock { #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(), ^{ if (returnBlock) { returnBlock(YES); } }); } else { dispatch_async(dispatch_get_main_queue(), ^{ if (returnBlock) { returnBlock(YES); } }); } }]; } else if (speechAuthStatus == SFSpeechRecognizerAuthorizationStatusAuthorized) { if (returnBlock) { returnBlock(YES); } } else{ if (returnBlock) { returnBlock(NO); } } #endif }
14.iOS開發(fā)檢測是否開啟媒體資料庫/Apple Music:
需要導入:
#import <MediaPlayer/MediaPlayer.h>
代碼如下:
#pragma mark - 開啟媒體資料庫/Apple Music 服務 + (void)openMediaPlayerServiceWithBlock:(ReturnBlock)returnBlock { #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(), ^{ if (returnBlock) { returnBlock(YES); } }); }else{ dispatch_async(dispatch_get_main_queue(), ^{ if (returnBlock) { returnBlock(NO); } }); } }]; }else if (authStatus == MPMediaLibraryAuthorizationStatusAuthorized){ if (returnBlock) { returnBlock(YES); } }else{ if (returnBlock) { returnBlock(NO); } } #endif }
15.iOS開發(fā)檢測是否開啟Siri:
需要導入:
#import <Intents/Intents.h>
代碼如下:
#pragma mark - 開啟Siri服務 + (void)openSiriServiceWithBlock:(ReturnBlock)returnBlock { #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(), ^{ if (returnBlock) { returnBlock(YES); } }); } else { dispatch_async(dispatch_get_main_queue(), ^{ if (returnBlock) { returnBlock(YES); } }); } }]; } else if (siriAutoStatus == INSiriAuthorizationStatusAuthorized) { if (returnBlock) { returnBlock(YES); } } else{ if (returnBlock) { returnBlock(NO); } } #endif }
在.h文件中申明block
#if NS_BLOCKS_AVAILABLE typedef void(^ReturnBlock)(BOOL isOpen); #endif
由于iOS10的權限原因,需要在工程的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>
感謝你能夠認真閱讀完這篇文章,希望小編分享的“iOS開發(fā)中如何檢測是否開啟定位、是否允許消息推送等權限”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業(yè)資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。