如何使用标识符连接外围设备/ BLE 设备?

How to connect peripheral/ BLE device by using identifier?

我想通过标识符连接外设。 我可以吗?

centralManager?.connect(peripheral, options: nil)

我正在一个 ViewController 中扫描设备并在另一个 ViewController 中连接它。

以下是我的要求:

当我扫描设备并保存下次可以出现在主屏幕并直接连接的设备时。 所以为此,我使用单例class从一个视图到另一个视图访问外围数据。但它总是初始化为空。 所以我想使用标识符连接外围设备。 我不知道我们在哪里存储 [CBPeripheral] 并在需要时访问它。

我想通过标识符连接外设。我可以吗?

简答: 不,你做不到。

长答案:

Refer apple official document.

There are no provision or method which is used to connect with an identifier But, Apple has provision to retrieve peripherals by using the identifier.

让我们讨论一些其他的选择

CBPeripheral 没有实现 NSCoding。因此,几乎不可能将 BLEPeripheral 对象存储到 NSUserDefaults 或任何其他容器中。

最好的解决方案是存储 CBPeripheral 的属性,例如名称或标识符等

UserDefaults.standard.set(Device_name, forKey: "Device_name")
UserDefaults.standard.set(Device_Identifier forKey: "Device_Identifier")

通过使用 retrievePeripherals(withIdentifiers:) 您可以再次获得 BLEPeripheral 值。然后你可以直接使用这个对象连接

Here is the documentation

检索外设(withIdentifiers:)

Returns a list of known peripherals by their identifiers.