Core Bluetooth: Find out if device is available for reconnection

时间:2019-01-18 18:41:06

标签: ios swift core-bluetooth

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?

1 个答案:

答案 0 :(得分:2)

“设备可用?”框表示已调用centralManager(_:didConnect:)。如果您查看上面的框,则为“尝试连接”。如果成功,则设备可用。

这几乎总是正确的方法。不要问“这有可能成功吗?”试一试。如果可以,那么可以。

如果您确实想知道附近但未连接的设备,则可以使用scanForPeripherals(withServices:options:)扫描它们是否在做广告。然后,您可以检查是否找到了所发现的外围设备。

当然,设备可能在附近并且没有广告。它可能已连接到另一台设备,在这种情况下您看不到它。它可能已连接到您的设备,在这种情况下,您需要retrieveConnectedPeripherals才能看到它。它可能只是不做广告(许多设备会在一段时间后停止做广告)。在这种情况下,如果不尝试连接它就看不到它。

但是通常正确的答案是,如果您已经知道设备,则尝试尝试连接。设置一个超时,如果超时,则可能不在附近。或不设置超时,只让它尝试连接直到起作用。