ff10
ff10

Reputation: 3147

Core Bluetooth: Find out if device is available for reconnection

I'm trying to use the retrievePeripheralsWithIdentifiers: method to try to connect to a previously connected peripheral. Connection attempts will only succeed when the peripheral is in vicinity of the iOS device.

Now, how do I figure out if the known peripheral is in vicinity and therefore connectable in the near future?

If you have a look at the Core Bluetooth guide here and scroll down to Figure 5.1 Apple describes a possible reconnection flow. In the first column of that diagram theres a conditional "Device available?" What method or member does reflect this availability?

Upvotes: 2

Views: 1313

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

The "Device available?" box is referring to centralManager(_:didConnect:) having been called. If you look at the box above, it's "Try to connect." If it's successful, then the device is available.

This is almost always the correct approach. Don't ask "is this likely to succeed?" Just try. If it works, it works.

If you really want to know nearby but unconnected devices, then you can scan for them if they're advertising using scanForPeripherals(withServices:options:). You can then check if any discovered peripherals are the one you're looking for.

Of course a device might be nearby and not advertising. It might be connected to another device, in which case you can't see it. It might be connected to your device, in which case you'll need retrieveConnectedPeripherals to see it. It might just be not advertising (many devices stop advertising after a period of time). In that case you can't see it without trying to connect to it.

But generally the right answer is to just try to connect if you know the device already. Set a timeout, and if it times out, it's probably not nearby. Or don't set a timeout, and just let it try to connect until it works.

Upvotes: 2

Related Questions