Search code examples
ioscore-bluetooth

How to capture the change of Bluetooth in iOS development?


Can we be notified in those situations? When iPhone's Bluetooth is on or off. When iPhone connects to or disconnect to another device by Bluetooth.


Solution

  • You can use CBCentralManager and add the CBCentralManagerDelegate methods to see when a peripheral device is connected / disconnected.

    centralManagerDidUpdateState will give information about your iOS device's bluetooth state.

    didConnectPeripheral and didDisconnectPeripheral can be used for monitoring connected devices when you connect to the device within your app using connect on your centralManager (seen in example below).

    If you know the identifier of the device you want to check for, you can use CBCentralManager's retrievePeripheralsWithIdentifiers to check the connection status for devices that are connected independent of your app.

    class ViewController: UIViewController, CBCentralManagerDelegate {
    
      var centralManager:CBCentralManager!
    
      override func viewDidLoad() {
        super.viewDidLoad()
        centralManager = CBCentralManager.init(delegate: self, queue: DispatchQueue.main)
      }
    
      func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == CBManagerState.poweredOn {
          centralManager.scanForPeripherals(withServices: nil, options: nil)
        }
      }
    
      func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        centralManager.connect(peripheral, options: nil)
      }
    
      func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("peripheral \(String(describing: peripheral.name)) connected")
      }
    
      func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("peripheral \(String(describing: peripheral.name)) disconnected")
      }
    }