Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continue BLE activities onto next view controller

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.

like image 633
Andrew F. Avatar asked Mar 21 '16 18:03

Andrew F.


1 Answers

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.
like image 96
dichen Avatar answered Oct 09 '22 08:10

dichen