监控 CBPeripheral 状态变化

Monitor CBPeripheral state changes

所以有一种方法可以通过 centralManagerDidUpdateState() 监视 CBCentralManager 的状态变化。但是是否有类似的方法调用来监视 CBPeripheral 的状态变化?我在 CoreBluetooth 库中找不到任何公开的内容,我想在 CBPeripheralState 更改时调用一个函数。

现在我只有一个检查外围设备状态的 switch 语句,但它总是 return 连接或断开连接。我怎样才能找到 connecting/disconnecting 个案例?我尝试将 switch 语句放在代码的各个部分,从 bleInit() 方法到 startScanning(), connectToPeripheral(),等等

switch(peripheral.state){
case .disconnected:
    print("disconnected")
case .connecting:
    print("connecting")
case .connected:
    print("connected")
case .disconnecting:
    print("disconnecting")
default: break
}

我认为 peripheralManagerDidUpdateState (https://developer.apple.com/reference/corebluetooth/cbperipheralmanagerdelegate/1393271-peripheralmanagerdidupdatestate) 是你想要的吗?

连接状态和断开状态是过渡状态。您的连接只会在很短的时间内处于这些状态;这就是为什么你永远不会看到那些状态。

如果您的应用程序充当中心,则通过 CBCentralManagerdidConnectdidDisconnectPeripheral 方法通知外围设备连接状态。

CBPeripheralstate 属性 是 KVO 兼容的,因此您可以轻松添加一个对象作为观察者并监视所有状态转换。

请注意,由于某些原因,某些状态转换很奇怪,即当外围设备从断开连接变为断开连接时没有任何中间状态。恐怕这是 CoreBluetooth 堆栈中的错误。