Search code examples
iosbluetooth-lowenergycore-bluetoothios-bluetooth

Reconnect to a BLE device after pulling the battery


I have a BLE device that I am writing an app to pair with. I can discover and connect to the device with no problems. But if I am connected and pull and reinsert the battery on the BLE device I get the didDisconnectPeripheral callback but I never get another didConnectPeripheral even though I'm still scanning. I also tried calling retrieveConnectedPeripheralsWithServices and retrievePeripheralsWithIdentifiers but neither of those return anything.

How can I reliably reconnect after cycling the power on my BLE device?


Solution

  • As soon as the peripheral disconnects you can issue another connect - iOS will automatically reconnect to the device once it is visible again and call your didConnectPeripheral: delegate method

    -(void) centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
        NSLog(@"Disconnected from peripheral");
        [central connectPeripheral:peripheral options:nil];
    }
    

    There is no need to rescan/re-discover the peripheral.

    You may want a more comprehensive implementation that updates UI etc.

    Here is some sample code that connects to a peripheral and displays the vendor information - https://github.com/paulw11/BTBackground