CBPeripheral始终连接到CBCentralManager,即使配对请求未成功

时间:2016-04-28 10:31:48

标签: ios objective-c core-bluetooth cbcentralmanager cbperipheral

我是iOS新手的核心蓝牙编程。最近我遇到了这个问题,当连接到外围设备时,屏幕上会弹出“蓝牙配对请求”警报。但无论我是否取消了请求,输入了无效的引脚,或者什么都不做,

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

委托总是被调用。这意味着连接总是成功的。谁能解释为什么会这样?感谢。

2 个答案:

答案 0 :(得分:0)

要连接到外围设备将触发(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;,因此如果BLE设备已启用配对,您将收到要求配对的提示。如果配对不成功,如果设备在配对不成功后没有断开连接的命令,它将保持连接,但如果你试图发现它的服务(*)和你可能没有得到的特征(取决于如何配置BLE设备的固件端。

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"Did connect to peripheral: %@", peripheral);

    [peripheral setDelegate:self];
    [peripheral discoverServices:nil];   //* discover peripheral services
}


- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
for (CBService *service in peripheral.services) {
        NSLog(@"discovered service [%@]",service.UUID);
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

答案 1 :(得分:0)

swift 3

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral){

           self.bleManager.stopScan()
           peripheral.discoverServices(nil)
    }
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {

          self.displayToastMessage("Fail to connect")
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?){

        if let er = error{
            self.displayToastMessage(er as! String)
            return
        }
        if let services = peripheral.services as [CBService]!{
            print(services)
        }
    }
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?){

            if let arraychar = service.characteristics as [CBCharacteristic]!{

                 for getCharacteristic in arraychar{

                      print(getCharacteristic)
                 }
            }
    }