我正在使用具有多个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) }
创建一个Singleton类,并在其中添加bleManager和外围设备属性:
class Shared { private init(){ } static let instance = Shared() var bleManager: BLEManager! var peripheral: CBPeripheral! }
您可以通过不同的控制器访问同一实例:
Shared.instance.bleManager = BLEManager()