1

Is there any why to detect CBPeripheral object state change from "Connected" to "Disconnected" in iOS.

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
a.palo
  • 258
  • 2
  • 12

1 Answers1

1

For detecting whether a Core Bluetooth Peripheral object is disconnected use a centralManager(_:didDisconnectPeripheral:error:) instance method which tells the delegate that the central manager disconnected from a peripheral:

     func centralManager(_ central: CBCentralManager, 
didDisconnectPeripheral peripheral: CBPeripheral, 
                             error: Error?) {

         print(peripheral.state)    // CBPeripheralState
     }

Do not forget to set a delegate instance property that is the delegate object specified to receive peripheral events from a CBPeripheralDelegate protocol that provides updates on the use of a peripheral’s services:

weak var delegate: CBPeripheralDelegate? { get set }

The CBPeripheralState has three cases:

enum CBPeripheralState : Int {

    case disconnected = 0
    case connecting = 1
    case connected = 2
}
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
  • 1
    Hi @Andy. I have already used the proposed solution to fix my issue. However, thank you for your response. – a.palo Apr 01 '20 at 08:42