How to continue BLE activities onto next view cont

2020-02-28 23:58发布

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.

1条回答
Lonely孤独者°
2楼-- · 2020-02-29 00:46

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.
查看更多
登录 后发表回答