简体   繁体   中英

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 .

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.

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.

Let's discuss some other alternatives

The CBPeripheral does not implement NSCoding. So, it is next to impossible to store BLEPeripheral object into NSUserDefaults OR any other container.

The best solution is to store the properties of CBPeripheral like name or identifier etc.

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. Then you can connect directly using this object

Here is the documentation

retrievePeripherals(withIdentifiers:)

Returns a list of known peripherals by their identifiers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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