监视 CB 外部设备状态更改



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

现在我只有一个 switch 语句来检查外围设备状态,但它总是只返回已连接或断开连接。如何进入连接/断开连接案例?我尝试将我的 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
}

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

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

CBPeripheralstate属性是符合KVO的,因此您可以轻松地将对象添加为观察者并监视所有状态转换。

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

我认为外围设备管理器DidUpdateState(https://developer.apple.com/reference/corebluetooth/cbperipheralmanagerdelegate/1393271-peripheralmanagerdidupdatestate(可以满足您的要求?

最新更新