BLE Peripheral disconnects when navigating to different ViewController

走远了吗. 提交于 2019-12-17 12:09:06

问题


I am working on BLE iOS (Swift) application which has multiple ViewControllers. The main ViewController has a button which navigates to TableViewController which has detected BLE devices to connect with. But when I return back to main or another view the peripheral device disconnects. I tried to pass peripheral from TableViewController to main ViewController but still, it disconnects.

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 activities onto next view controller


回答1:


Create a Singleton class and add bleManager and peripheral properties there:

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

And you can access the same instance through different controllers:

Shared.instance.bleManager = BLEManager() 


来源:https://stackoverflow.com/questions/47477776/ble-peripheral-disconnects-when-navigating-to-different-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!