How to detect if a non-connected peripheral leaves range in Swift?

626 views Asked by At

Writing in app in Swift, using CoreBluetooth, is there any way without constantly re-scanning, to detect if a peripheral which I'm not connected to, is no longer nearby.

1

There are 1 answers

0
Paulw11 On

Independent of the language, if you are not connected to the peripheral then there is no simple notification when a peripheral is no longer in range.

The only solution is to use CBCentralManagerScanOptionAllowDuplicatesKey in the options of scanForPeripheralsWithServices and maintain a list of known peripherals, ageing them out of the list when they stop being reported.

For example -

  • Create a dictionary
  • When a peripheral is reported add it to the dictionary (use the string of the ID as the key) with an Int value of 30
  • Create an NSTimer that fires every second
  • When the timer fires, iterate through the dictionary, decrementing each Int.
  • If the Int reaches zero, remove that peripheral from the dictionary