So there's a way to monitor state changes of CBCentralManager
via centralManagerDidUpdateState()
. But is there a similar method call to monitor state changes for CBPeripheral
? I couldn't find anything exposed in CoreBluetooth
library, and I want to call a function whenever CBPeripheralState
changes.
Right now all I have is a switch statement which checks the peripheral state, but it'll always just return either connected or disconnected. How would I get to the connecting/disconnecting cases? I've tried placing my switch statement in various parts of my code, from the bleInit()
method, to startScanning(), connectToPeripheral()
, etc
switch(peripheral.state){
case .disconnected:
print("disconnected")
case .connecting:
print("connecting")
case .connected:
print("connected")
case .disconnecting:
print("disconnecting")
default: break
}
The connecting and disconnecting states are transitionary states. Your connection will only be in those states for a very brief time; which is why you will never see those states.
If your app is acting as a central then peripheral connection state is notified via the CBCentralManager
's didConnect
and didDisconnectPeripheral
methods.
CBPeripheral
's state
property is KVO-compliant, hence you can easily add an object as observer and monitor all state transitions.
Note though that for some reason some state transitions are strange, i.e. when a peripheral moves from disconnected to disconnecting without any intermediate states. I'm afraid that's bugs in the CoreBluetooth stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With