How do you scan for the same BLE device twice?

2019-08-09 01:51发布

问题:

I have an iOS app that scans for BLE peripherals, of which there may be many, and allows the user to decide whether or not to connect to the device. Once connected, the user can also decide to break the connection. All of this works fine.

I would also like to add an option to allow the user to change their mind and rescan for a device, but this seems to be problematic. The most obvious way to do this seems to be to stop scanning and restart it, as in:

    [centralManager stopScan];

    CBUUID *myServiceUUID = [CBUUID UUIDWithString: SERVICE_MYSERVICE];
    NSArray *services = [[NSArray alloc] initWithObjects: myServiceUUID, nil];
    [centralManager scanForPeripheralsWithServices: services options: nil];

This does not work.

Eventually, iOS decides to tell my app the device is advertising again, but this takes several minutes.

How can I convince iOS to tell me about the peripheral a second time without waiting several minutes?

回答1:

You can just enable the CBCentralManagerScanOptionAllowDuplicatesKey option when you init your CBCentralManager. You'll get constant callbacks when your app is in the foreground, however, you need to keep in mind that the CBCentralManagerScanOptionAllowDuplicatesKey is disabled in when the app is in the background. Also, the scanning interval is throttled to a ~60th of its foreground counterpart.