1

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

M. Wojcik
  • 2,301
  • 3
  • 23
  • 31
  • 1
    You can use a Singleton (it's a design pattern) for that. Create a class that is "unique" meaning it's returning always the same object (that's why it's called a singleton) that manage your CBCentral. – Larme Dec 08 '17 at 18:37
  • So whenever I put array of connected devices in a singleton object of that class, than anywhere in the app's class when I instantiate that singleton it will have that array for whole app life cycle? – M. Wojcik Dec 11 '17 at 09:19

1 Answers1

0

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

Neo
  • 1,359
  • 14
  • 34