I have a custom framework that allows you to handle all Bluetooth actions, such as connect, scan, etc. Additionally, I have two applications using this framework: a test app and a real app. I'm trying to implement auto-reconnection for turning Bluetooth off/on and out of range. While it works well in my test app, it doesn't in the real app. Here is my logic:
Firstly, I scan for a peripheral with a specific service UUID:
manager.scanForPeripherals(withServices: [self.targetUuid], options: scanOptions)
As a result, I have a CoreBluetooth callback response:
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber)
Then I connect to the peripheral:
connect(cbPeripheral, options: options)
And as a result:
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)
After that, I save the UUID as a String. Then, I try to disconnect the peripheral from the phone (turn BT off/on or go out of range) and connect back.
I've investigated different behaviours and found that in my test app, I have the same peripheral UUID even after disconnection, but in the real app, the UUID changes.
I found this:
The UUID will stay constant for a peripheral with randomized addresses for paired devices only for the lifetime of the pairing.
If a device is not paired, according to the LE Privacy rules (RRA), the UUID will change as a peer unit is neither capable nor supposed to track a device across changing addresses.
And this:
Connection attempts do not time out (as stated in the Apple documentation: [link]). Just be sure to also keep a reference to the peripheral object; otherwise, the connection gets canceled.
Here is my logic for reconnection in case of being out of range:
centralManager(_:didDisconnectPeripheral:error:)
[ERROR] - Peripheral was disconnected error -> Optional(Error Domain=CBErrorDomain Code=6 "The connection has timed out unexpectedly." UserInfo={NSLocalizedDescription=The connection has timed out unexpectedly.})
connect(cbPeripheral, options: options)
My question is:
What can affect UUID changing? Do I need to store a whole Peripheral Device object instead of UUID string?