【问题标题】:BLE Peripheral disconnects when navigating to different ViewController导航到不同的 ViewController 时 BLE 外设断开连接
【发布时间】:2026-02-01 08:40:01
【问题描述】:

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

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

【问题讨论】:

    标签: ios swift core-bluetooth


    【解决方案1】:

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

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

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

    Shared.instance.bleManager = BLEManager() 
    

    【讨论】: