【问题标题】:CBPeripheral always connects to CBCentralManager even Pairing Request was unsuccessful即使配对请求不成功,CBPeripheral 也始终连接到 CBCentralManager
【发布时间】:2016-08-23 01:28:40
【问题描述】:

我是 iOS 中 Core 蓝牙编程的新手。最近我遇到这个问题,当连接到外围设备时,屏幕上会弹出“蓝牙配对请求”警报。但不管我是取消了请求,输入了无效的密码,还是什么都不做,

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

delegate 总是被调用。这意味着连接总是成功的。谁能解释为什么会发生这种情况?谢谢。

【问题讨论】:

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


    【解决方案1】:

    连接到外围设备将触发(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];
        }
    }
    

    【讨论】:

      【解决方案2】:

      斯威夫特 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)
                       }
                  }
          }
      

      【讨论】:

        猜你喜欢
        • 2021-05-15
        • 2017-03-13
        • 2011-12-30
        • 2017-06-10
        • 2016-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-06
        相关资源
        最近更新 更多