iOS how to reconnect to BLE device in background?

Andrew Duncan picture Andrew Duncan · Nov 12, 2014 · Viewed 9k times · Source

There are many related questions but (apparently) no answers. SO...

My iOS app does get updates from my BLE device while the app is in background. If I lose touch with the BLE device, then in centralManager:didDisconnectPeripheral: I call -[CBCentralManager cancelPeripheralConnection:] -- otherwise I will never reconnect to the lost peripheral. Then I call [(re)call -[CBCentralManager scanForPeripheralsWithServices:options:].

Logging shows me that the didDisconnectPeripheral call, and its contained calls, are both happening while in background. However, the reconnect only happens when the app wakes up from background.

So I am able to communicate with the connected BLE device while in background (yay!) but not to reconnect. This is quite important to my app, and (one would think) to other apps. Suggestions welcome.

Answer

Andrew Duncan picture Andrew Duncan · Nov 14, 2014

Paul was correct, that I did not need to cancel the connection, and that I did not need to rescan, and that all I needed to do was call connectPeripheral. BUT... what I was not doing was this:

_manager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)];

I was passing nil for the queue, which meant my CBCentralManagerDelegate callbacks were running on the main thread.