简体   繁体   中英

iOS how to reconnect to BLE device in background?

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.

You don't need to cancel the connection - it is already disconnected You don't need to rescan for the peripheral - you have already identified your peripheral.

In didDisconnectPeripheral you can simply call

[central connectPeripheral:peripheral options:nil];

Core Bluetooth will reconnect once the peripheral is visible again

A complete sample is here - https://github.com/paulw11/BTBackground

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.

I know you probably have everything figured out already. I my self stumbled on this issue as well. Doing the following alone would not completely solve the problem (at least for me):
[central connectPeripheral:peripheral options:nil];

Instead of "nil" for the options, you will need to provide "options" in the above method. There are other things you need to set up as well (such as info.plist for your app). After reading Apple's instruction on how to enable background bluetooth operation for an App. I was able to get it working and receiving events for connect,disconnect,update etc., even scan can work in the back ground. Not to repeat everything what the Apple document has written about, you can take a look at the following link:
Core Bluetooth Background Processing for iOS Apps

Hope this helps.

在“功能” - >“背景模式”选项卡中,选择“用户蓝牙LE配件”和“充当蓝牙LE配件”。我不确定它是否可以工作,但您可以尝试一下。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM