iOS蓝牙开发连接系统或其他APP已经连接、配对成功的蓝牙设备

在蓝牙开发的时候,扫描外设的方法扫描到的设备只能是没有被连接的设备,也就是说如果有设备在本手机中已经连接配对成功了之后就不会被
[_centralManager scanForPeripheralsWithServices:nil options:nil];方法扫描到,一开始的手自己也没有注意到这个问题,结果在老板使用的工程中,老是出现系统已经连接上蓝牙设备了,然后就找不到设备了的情况,无奈,是时候正面这个问题了,在网上找了相关资料,原来只需要几行简单的代码就能实现。

下面贴代码

//已经被系统或者其他APP连接上的设备数组
            NSArray *arr = [_centralManager retrieveConnectedPeripheralsWithServices:@[[CBUUID UUIDWithString:serviceUUID0],[CBUUID UUIDWithString:characteristicUUID4],[CBUUID UUIDWithString:characteristicHeartUUID0]]]; //UUID是外设的服务UUID,满足UUID 的外设就会放在数组中
             [arr enumerateObjectsUsingBlock:^(CBPeripheral *obj, NSUInteger idx, BOOL *stop) {
                 NSLog(@"连接=====%@ %lu   /n%@",obj,(unsigned long)idx,obj.services);
                 [self discoverANCS:obj];
             }];
//其中,外设的UUID在

-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error中能够拿到


然后使系统、其他APP已经连接的设备在本App中可发现:

- (void)discoverANCS:(CBPeripheral *)peripheral{
    [self centralManager:_centralManager
   didDiscoverPeripheral:peripheral
       advertisementData:[NSDictionary dictionary]
                    RSSI:@(0)];
}


  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
iOS应用程序可以使用Core Bluetooth框架与蓝牙设备建立连接。以下是连接蓝牙设备的一般步骤: 1. 导入Core Bluetooth框架并设置中央管理器(CBCentralManager): ``` import CoreBluetooth var centralManager: CBCentralManager! override func viewDidLoad() { super.viewDidLoad() centralManager = CBCentralManager(delegate: self, queue: nil) } ``` 2. 扫描可用的蓝牙设备: ``` // 开始扫描 centralManager.scanForPeripherals(withServices: nil, options: nil) // 扫描到设备后调用该方法 func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // 处理扫描到的设备 } ``` 3. 连接蓝牙设备: ``` // 连接设备 centralManager.connect(peripheral, options: nil) // 连接成功后调用该方法 func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { // 处理连接成功事件 } ``` 4. 发现服务和特征: ``` // 发现设备的服务 peripheral.discoverServices(nil) // 发现服务后调用该方法 func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { // 处理发现服务事件 } // 发现服务的特征 peripheral.discoverCharacteristics(nil, for: service) // 发现特征后调用该方法 func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { // 处理发现特征事件 } ``` 5. 与蓝牙设备进行数据交换: ``` // 发送数据 peripheral.writeValue(data, for: characteristic, type: .withResponse) // 接收数据 func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { // 处理接收到的数据 } ``` 注意:在使用Core Bluetooth框架时,需要在应用程序的Info.plist文件中添加一个NSBluetoothPeripheralUsageDescription键,并提供一个描述字符串,以便在您的应用程序首次尝试连接蓝牙设备时向用户请求授权。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值