【发布时间】:2012-10-28 11:58:12
【问题描述】:
在Core Bluetooth中,连接到设备后,我关闭设备,设备断开连接。但是当我再次打开设备时,没有再次调用didDiscoverPeripheral。如何重新连接到设备?
【问题讨论】:
-
如何断开设备与外围设备的连接?
标签: ios bluetooth core-bluetooth
在Core Bluetooth中,连接到设备后,我关闭设备,设备断开连接。但是当我再次打开设备时,没有再次调用didDiscoverPeripheral。如何重新连接到设备?
【问题讨论】:
标签: ios bluetooth core-bluetooth
当您使用scanForPeripheralsWithServices 进行扫描时,它通常只会针对特定设备地址通知您一次。您可以通过指定选项CBCentralManagerScanOptionAllowDuplicatesKey 将其更改为报告重复项。或者,您可以让您的应用检测到另一台设备使用超时断开连接,然后重新开始扫描。
【讨论】:
当您使用cancelPeripheralConnection 断开设备连接时,将调用didDisconnectPeripheral 委托方法。但是,从 iOS 6.0 开始,设备会保持连接状态大约 40-50 秒(或更长时间),因此在该时间范围内不会调用 didDiscoverPeripheral。如果您想再次“发现”它,只需调用retrieveConnectedPeripherals 方法,您将在didRetrieveConnectedPeripherals 中获得参考。
但是,最好的解决方案是保存设备的 UUID 并使用它通过 retrievePeripherals 方法重新连接。这将调用didRetrievePeripherals,您可以使用connectPeripheral 重新连接。这是重新连接到设备的最快方式,在这种情况下不需要扫描。
【讨论】:
在 CoreBluetooth 中,所有管理都由应用层完成。 在你的情况下,我会做的是监听断开事件而不是在同一事件中,重新连接外围设备。 该连接方法价格低廉,可确保您在设备恢复范围后重新连接。
请注意,如果您明确断开设备,您会收到相同的断开事件,但您不必调用重新连接方法。
【讨论】:
@Andras 给了我正确的道路,但他的答案从 iOS7 开始就不完整了。
重新连接到以前的设备的最佳方法是使用retrievePeripherals(withIdentifiers:) 方法。
该方法不调用委托,而是直接返回给你一个Peripherals的列表,对应传入参数的UUID列表。
if let peripheral = self.centralManager.retrievePeripherals(withIdentifiers: [uuid]).first {
self.peripheral = peripheral // <-- super important
self.centralManager.connect(peripheral, options: nil)
}
请检查上面代码的“超级重要”行:方法connect(_:option:)不保留外设,如果你不自己做,连接总是失败,没有任何回调,因为外设对象会被摧毁。
【讨论】: