美文网首页
使用CoreBluetooth判断蓝牙设备连接状态

使用CoreBluetooth判断蓝牙设备连接状态

作者: 卖艺小青年o0 | 来源:发表于2021-07-21 17:14 被阅读0次

     工作中需要判断蓝牙设备是否连接的需求,网上查了不少资料,发现有提供AVAudioSession判断是否连接的方法

    /**

    检测是否连接蓝牙

    @return 是否为蓝牙音频输出、

    */

    -(BOOL)isBleToothOutput

    {

        AVAudioSessionRouteDescription *currentRount = [AVAudioSession sharedInstance].currentRoute;

        AVAudioSessionPortDescription *outputPortDesc = currentRount.outputs[0];

        if([outputPortDesc.portType isEqualToString:@"BluetoothA2DPOutput"]){

            NSLog(@"当前输出的线路是蓝牙输出,并且已连接");

            return YES;

        }else{

            NSLog(@"当前是spearKer输出");

            return NO;

        }

    }

    使用后发现,此方法只能获取到是否连接蓝牙音频设备,而不适用于非音频设备。

    随后查询资料发现官方提供的CoreBluetooth库,可以获取到蓝牙开启状态,细看其官方文档发现

    //扫描到设备会进入方法
    -(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI

    在这个代理回调中会返回外设(peripheral),外设数据(advertisementData),外设信号强度(RSSI),对比查看官方文档发现外设(peripheral),外设数据(advertisementData)两个数据有返回是否连接的状态属性:

    外设(peripheral)的属性 外设数据(advertisementData)的属

     通过测试发现第一个属性在didDiscoverPeripheral回调中是不会改变的(猜测可能需要通过api连接之后,才会刷新状态),而外设数据(advertisementData)可以获取到。

    获取连接状态代码:

        NSInteger connectState = [[advertisementData valueForKey:@"kCBAdvDataIsConnectable"] integerValue];

        if(connectState ==1) {

            return 已连接

        }

      return 未连接

    相关文章

      网友评论

          本文标题:使用CoreBluetooth判断蓝牙设备连接状态

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