导航到不同的ViewController时,BLE外围设备断开连接 [英] BLE Peripheral disconnects when navigating to different ViewController
问题描述
我正在研究具有多个ViewControllers的BLE iOS(Swift)应用程序。主ViewController有一个按钮,导航到TableViewController,它检测到要连接的BLE设备。但当我返回主视图或其他视图时,外围设备断开连接。我试图将外围设备从TableViewController传递到主ViewController,但仍然断开连接。
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)
}
推荐答案
创建一个Singleton类并在那里添加bleManager和外围属性:
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()
这篇关于导航到不同的ViewController时,BLE外围设备断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!