美文网首页
iOS 获取设备蓝牙状态

iOS 获取设备蓝牙状态

作者: 狂暴的小蜗牛 | 来源:发表于2020-07-20 11:24 被阅读0次

    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];
    }

    相关文章

      网友评论

          本文标题:iOS 获取设备蓝牙状态

          本文链接:https://www.haomeiwen.com/subject/dquekktx.html