BLE 外设在导航到不同 ViewController 时断开连接

BLE Peripheral disconnects when navigating to different ViewController

我正在开发具有多个 ViewController 的 BLE iOS (Swift) 应用程序。主 ViewController 有一个按钮,可导航到已检测到要连接的 BLE 设备的表 ViewController。但是当我 return 回到主视图或另一个视图时,外围设备断开连接。我试图将外围设备从 TableViewController 传递到 main ViewController 但它仍然断开连接。

主要ViewController:

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)
}

创建一个 Singleton class 并在其中添加 bleManager 和外围属性:

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

并且您可以通过不同的控制器访问同一个实例:

Shared.instance.bleManager = BLEManager()