我正在研究具有多个ViewControllers的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)
}
答案 0 :(得分:4)
创建一个Singleton类并在那里添加bleManager和外围属性:
class Shared {
private init(){ }
static let instance = Shared()
var bleManager: BLEManager!
var peripheral: CBPeripheral!
}
您可以通过不同的控制器访问同一个实例:
Shared.instance.bleManager = BLEManager()