简体   繁体   English

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

[英]How to connect peripheral/ BLE device by using identifier?

I want to connect the peripheral by using an identifier. 我想使用标识符连接外围设备。 Can I do it? 我可以做吗?

centralManager?.connect(peripheral, options: nil)

I am scanning devices in one ViewController and Connecting it in another ViewController . 我在一个ViewController扫描设备,然后在另一个ViewController连接设备。

Below is my requirement: 以下是我的要求:

When I scanned device and saved the next time the device that can appear in home screen and directly connected. 当我扫描设备并下次保存时,该设备可以显示在主屏幕中并直接连接。 So for this, I use singleton class to access peripheral data from one view to another view. 因此,为此,我使用单例类从一个视图访问另一视图的外围数据。 But it always initializes to empty. 但是它总是初始化为空。 So I want to connect peripheral by using an identifier. 所以我想使用标识符连接外围设备。 I don't know where we store [CBPeripheral] and access it when needed. 我不知道我们在哪里存储[CBPeripheral]并在需要时访问它。

I want to connect the peripheral by using an identifier. 我想使用标识符连接外围设备。 Can I do it? 我可以做吗?

Short answer: NO, You can't do it. 简短的回答:不,您不能这样做。

Long answer: 长答案:

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. 没有用于与标识符连接的规定或方法,但是,Apple规定使用标识符来检索外围设备。

Let's discuss some other alternatives 让我们讨论其他一些选择

The CBPeripheral does not implement NSCoding. CBPeripheral不实现NSCoding。 So, it is next to impossible to store BLEPeripheral object into NSUserDefaults OR any other container. 因此,几乎不可能将BLEPeripheral对象存储到NSUserDefaults或任何其他容器中。

The best solution is to store the properties of CBPeripheral like name or identifier etc. 最好的解决方案是存储CBPeripheral的属性,例如名称或标识符等。

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

By using retrievePeripherals(withIdentifiers:) you can get BLEPeripheral value again. 通过使用retrievePeripherals(withIdentifiers:)您可以再次获取BLEPeripheral值。 Then you can connect directly using this object 然后您可以使用该对象直接连接

Here is the documentation 这是文档

retrievePeripherals(withIdentifiers:) retrievePeripherals(withIdentifiers :)

Returns a list of known peripherals by their identifiers. 通过标识符返回已知外围设备的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM