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

Vik*_*kas 0 ios core-bluetooth bluetooth-lowenergy swift

我想通过使用标识符连接外围设备。我可以做吗?

centralManager?.connect(peripheral, options: nil)
Run Code Online (Sandbox Code Playgroud)

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

以下是我的要求:

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

Hit*_*esh 5

我想通过使用标识符连接外围设备。我可以做吗?

简短的回答: 不,你做不到。

长答案:

参考苹果官方文档。

没有用于连接标识符的规定或方法,但是,Apple 提供了使用标识符检索外围设备的规定。

让我们讨论一些其他替代方案

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

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

UserDefaults.standard.set(Device_name, forKey: "Device_name")
UserDefaults.standard.set(Device_Identifier forKey: "Device_Identifier")
Run Code Online (Sandbox Code Playgroud)

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

这是文档

检索外设(带有标识符:)

按标识符返回已知外围设备的列表。