iOS 获取设备蓝牙状态

1.导入头文件 #import <CoreBluetooth/CoreBluetooth.h>

2.添加<CBCentralManagerDelegate>

3.@property (nonatomic, strong) CBCentralManager *centralManager;

4.初始化属性

- (void)subPropertiesInit {// 初始化属性
    // 初始化管理者
    // CBCentralManagerOptionShowPowerAlertKey
   //_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

    _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey:    [NSNumber numberWithBool:NO]}];

}

5.实现代理 #pragma mark -- CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager*)central
{
    switch(central.state) {
    case CBManagerStateUnknown:
        NSLog(@"central.state = CBManagerStateUnknown");
        break;
        case CBManagerStateResetting:
        {
            //[self showAlertViewTitle:@"Note!" message:@"Your apple device has bluetooth reset, please close the APP and reopen." rescan:NO];
            NSLog(@"central.state = CBManagerStateResetting .........iPhone正在重置蓝牙");
        }
            break;
        case CBManagerStateUnsupported:
            NSLog(@"central.state = CBManagerStateUnsupported");
            break;
        case CBManagerStateUnauthorized:
            NSLog(@"central.state = CBManagerStateUnauthorized");
            break;
        case CBManagerStatePoweredOff: {
            NSLog(@"centralManager 未开启蓝牙..");
            [self bluetoothAlert];
            // 代理监控蓝牙未开启,状态改为正在扫描中
        }
        break;
        case CBManagerStatePoweredOn:
         {
            NSLog(@"centralManager 已开启蓝牙..");
          }
            break;
    }
}

6.前往设置界面开启蓝牙 #pragma mark - alert

-(void)bluetoothAlert{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"前往设置界面开启蓝牙功能" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *setBtn = [UIAlertAction actionWithTitle:@"开启蓝牙" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       [self ibeaconState];
   }];
   UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
   [alertController addAction:setBtn];
   [alertController addAction:cancelAction];
   [self presentViewController:alertController animated:YES completion:nil];
}

7.跳转设置界面

-(void)ibeaconState{
  NSURL *url = [NSURL   URLWithString:UIApplicationOpenSettingsURLString];
 [[UIApplication sharedApplication]openURL:url];
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。