gpt4 book ai didi

ios - 导航到不同的 ViewController 时 BLE 外设断开连接

转载 作者:搜寻专家 更新时间:2023-10-31 08:29:57 25 4
gpt4 key购买 nike

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

主视图 Controller :

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

最佳答案

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

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

并且可以通过不同的 Controller 访问同一个实例:

Shared.instance.bleManager = BLEManager() 

关于ios - 导航到不同的 ViewController 时 BLE 外设断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47477776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com