How to detect with CoreBluetooth when a peripheral disappears?

6.8k views Asked by At

I would like to have a list of ble devices to which my iOS can connect, which refreshes when ble devices appear and disappear.

In order to do that, I created an NSMutableDictionnary* peripheralsAvailable, and everytime - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; is called by the CBCentralManager, I add the peripheral to the peripheralsAvailable dictionnary (and then update a UITableView). All is OK here.

However I can't find how I can update the dictionnary if a Peripheral "disappear". It seems that I can only add peripherals in my dictionnary when they are detected, but I can't remove one when I shut it down for example.

Could you tell me if I'm missing something?

2

There are 2 answers

3
Marcus Adams On BEST ANSWER

The OS will cache discovery of devices. I.e. you will only get one "discovery" event per device.

To continuously get discovery events while the peripheral is advertising, you must use the following option:

CBCentralManagerScanOptionAllowDuplicatesKey

A Boolean value that specifies whether the scan should run without duplicate filtering.

The value for this key is an NSNumber object. If YES, filtering is disabled and a discovery event is generated each time the central receives an advertising packet from the peripheral. Disabling this filtering can have an adverse effect on battery life and should be used only if necessary. If NO, multiple discoveries of the same peripheral are coalesced into a single discovery event. If the key is not specified, the default value is NO.

Setting the above option to YES, you could keep track of all of the peripherals that are advertising and when it stops advertising, you could remove it from the list.

For a device that you've connected to, there is the didDisconnectPeripheral delegate event.


Bluetooth devices don't advertise that they're about to go away, nor do they advertise that you're about to go out of range. You get an advertisement while they're advertising and you're within range, and you get nothing when you're out of range or they stop advertising. There's no event to trigger on when they're gone. You have to remember the devices that are advertising, and when they stop advertising (you haven't received an advertisement in awhile), you can remove it from the list.

0
diabetesmike On

Great answer by Marcus. One additional note to add is that the scan option CBCentralManagerScanOptionAllowDuplicatesKey as mentioned above does not work in the background.

Apps that have specified the bluetooth-central background mode are allowed to scan while in the background. That said, they must explicitly scan for one or more services by specifying them in the serviceUUIDs parameter. The CBCentralManager scan option is ignored while scanning in the background.