iosswiftswift3core-bluetoothcbperipheral

Monitor CBPeripheral state changes


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
}

Solution

  • 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.