6

I am developing an app which scans for nearby BLE devices, connect to one of them, and communicate to the connected device. I tried to do it in 2 view controllers, controller-A and controller-B. Controller-A would scan for nearby devices and connect to one of them. Controller-B would exchange data to the connected device. Controller-A extends CBCentralManagerDelegate. My problem is: when my app switch to view controller-B, it does not get the call-backs from CBCentralManager. I have to initialize CBCentralManager again in controller-B. I also have to disconnected the device from controller-A, and reconnect in controller-B. Is there a better way to do it? Thanks.

Andrew F.
  • 267
  • 2
  • 11

1 Answers1

7

Put your BLE related code into a centralized place, e.g. BLEMaganer (better) or AppDelegate (so so). So that controllerA and controllerB can share the same centrolManager instance.

For example, currently you have a property centralManager in controllerA, and implement its delegate in controllerA. You access centralManager by controllerA.centralManager.

Move the centralManager property to AppDelegate, as well other related code. Then you can access centrolManager instance by

(UIApplication.sharedApplication().delegate as! AppDelegate).centralManager.
dichen
  • 1,643
  • 14
  • 19
  • In that centralized place, how do I send data back to controllerA and controllerB. ControllerA and controllerB are not singleton. How do I know that the data are sent back to the instance I am running on my screen? Thanks. – Andrew F. Mar 21 '16 at 20:45
  • I understand how to access the sharedApplication. The problem is: how to get the data back from the sharedApplication back to controllerA. For example, after getting the nearby devices, how does the sharedApplication send the device names back to controllerA. Thanks. – Andrew F. Mar 21 '16 at 23:59
  • Currently you implement the delegate in controllerA, when it get called you update the views. Now the delegate is implement in AppDelegate, so you need a way to notify controllerA, that data is ready. I prefer NSNotification. – dichen Mar 22 '16 at 00:18
  • 2
    Works great! I put all the ble stuff in a separate class. I instantiate the ble class from my controllerA. When I pass control to controllerB, I pass the instance to controllerB in prepareForSegue. So, I use the same instance the whole time. I use NSNotificationCenter.defaultCenter() for sending data back to the controllers. I also use static variables in the controllers so the ble class can change them directly. Thanks for your suggestions, dichen. – Andrew F. Mar 22 '16 at 20:56
  • Great, glad to help. – dichen Mar 22 '16 at 20:59