centralManager:didDiscover peripheral is called even though the other device has stopped advertising

Hello,


I'm trying to get a little smarter about core Bluetooth. :-)

I have an app on device 1 which advertises a service using

        peripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey:[serviceCBUUID],
                                            CBAdvertisementDataLocalNameKey: localName])


On a second device I use

            centralManager.scanForPeripherals(withServices: [serviceCBUUID],
                                              options: [CBCentralManagerScanOptionAllowDuplicatesKey:true])

to be notified as soon as a device with the desired service is available.


So far everything works without any problems.

However, if I carry out the following steps on device 1:

  • Put the app in background (the corresponding background mode is activated)
  • Bring the app back to foreground.
  • End the advertising of the service with
        peripheralManager.removeAllServices()
        peripheralManager.stopAdvertising()

Then the following delegate method is still called on device 2.

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber)

The strange thing is that even when I connect to the device and use

peripheral.discoverServices([serviceCBUUID])

to ask for my service, I get an empty list. Which is ok, since I've stopped avertising on device 1, but why is the device detected at all when I explicitly ask for devices that provide my service?


This only happens, when I put the app in background on device 1. If I keep it in foreground, the delegate method on device 2 is no longer called as soon as I stop advertising on device 1.


I need to turn bluetooth off in settings on device 1 to stop this. Restarting the app and stopping advertising does nothing.


BR

Dirk