swiftbluetoothsavestatecbperipheralcbcentralmanager

Swift 4 save CBPeripherals array save state when returning to controller


So I am working with Bluetooth connections and I have an array of connected devices (some sensors). The problem in the devices is that, whenever there is something connected to that devices, CBCentralManager scanning doesnt find them (thats how they work). That's why I have to make an array of CBPeripherals that are connected an I want to display it in TableView where I display also not connected devices (the ones found while scanning).

Now, the problem is, whenever I put something into my connectedDevices:[CBPeripheral] array and I go back from my controller, and than return to it, the connectedDivecies array is empty. Thats absolutely normal and I understand it.

So the question is, how can I, in swift, store that array so whenever I return to that controller it holds same data, I mean - same CBPeripheral objects? I tried to do it with UserDefaults but nothing seems to work.

Please give me some ideas on how to manage that


Solution

  • Just keep your devices list in the AppDelegate

    then access it using something like

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let aVariable = appDelegate.someVariable
    

    Although there is a lot of discussion on whether to use App Delegate as A singleton for storing your objects. IMHO storing an array of objects that's small won't harm your app anyway