Search code examples
iosswiftbluetoothbluetooth-lowenergycore-bluetooth

Unable to reconnect after cancelling BLE peripheral connection iOS


In my project I was successful to connect to a Bluetooth LE peripheral and read CBCharacteristic value from that device. I am facing an issue. I need to disconnect the peripheral and reconnect the device again if user wishes.

I am using the following steps.

1. For Disconnecting: I am calling centralManager?.cancelPeripheralConnection(peripheral). This call is completed successfully calling delegate func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?)

2. To Reconnect: I start scanning for peripherals, as I did when the app launched centralManager!.scanForPeripheralsWithServices(nil, options: nil)

But this call never calls the delegate func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) where I try to connect the BLE discovered peripheral.

My question is what is the best practice to disconnect a BLE peripheral and reconnect it again in iOS. Am I doing anything wrong?


Solution

  • Thats not the right way to re-connect to BLE.

    Per Apple Documentation:

    Reconnecting to Peripherals

    Using the Core Bluetooth framework, there are three ways you can reconnect to a peripheral. You can:

    1. Retrieve a list of known peripherals—peripherals that you’ve discovered or connected to in the past—using the
      retrievePeripheralsWithIdentifiers: method. If the peripheral you’re looking for is in the list, try to connect to it. This reconnection
      option is described in Retrieving a List of Known Peripherals.
    2. Retrieve a list of peripheral devices that are currently connected to the system using the retrieveConnectedPeripheralsWithServices: method. If the peripheral you’re looking for is in the list, connect
      it locally to your app. This reconnection option is described in
      Retrieving a List of Connected Peripherals.
    3. Scan for and discover a peripheral using the scanForPeripheralsWithServices:options: method. If you find it, connect to it. These steps are described in Discovering Peripheral Devices That Are Advertising and Connecting to a Peripheral Device After You’ve Discovered It.