BLE Peripheral Disconnections When Switching to Another ViewController

I am working on a BLE iOS application (Swift) that has several ViewControllers. The main ViewController has a button that moves to the TableViewController, which has detected BLE devices to connect to. But when I return to the main or another kind, the peripheral device turns off. I tried to transfer the peripherals from the TableViewController to the main ViewController, but still it shuts down.

MainViewController:

var bleManager: BLEManager! var peripheral: CBPeripheral! override func viewDidLoad() { bleManager = BLEManager() super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { if let peripheral = self.peripheral { do { print("Value from display = \(peripheral.state)") } } } func setPeripheral(sent: CBPeripheral) { self.peripheral = sent } @IBAction func manageDevice(sender: UIButton) { // 1. Instantiate TableViewController let tableViewController = self.storyboard?.instantiateViewController(withIdentifier: "TableViewController") as! TableViewController // 2. Set self as a value to delegate tableViewController.delegate = self // 3. Push SecondViewController self.navigationController?.pushViewController(tableViewController, animated: true) } 

How to continue BLE on the next view controller

+2
ios swift core-bluetooth
source share
1 answer

Create a Singleton class and add the bleManager properties and peripherals:

 class Shared { private init(){ } static let instance = Shared() var bleManager: BLEManager! var peripheral: CBPeripheral! } 

And you can access one instance through different controllers:

 Shared.instance.bleManager = BLEManager() 
+3
source share

All Articles