ios - 核心蓝牙 : CBPeripheral disconnects unknowingly and not getting any call to didDisconnectPeripheral

标签 ios swift core-bluetooth cbcentralmanager

我有 3 个 ViewController。 1)首页VC 2)扫描VC 3) 连接VC

步骤: 我从 Home VC 推送到 Scan VC 以扫描可用的 BLE 设备。

扫描VC:我这里有所有的BLE通信代码:

override func viewDidLoad() {
        super.viewDidLoad()

            AppConstants.sharedInstance.centralManager = CBCentralManager(delegate: self, queue: nil) // created global Instance for central Manager and assigned it here
    }

上面将调用 centralManagerDidUpdateState(_ central: CBCentralManager) 我正在检查蓝牙的所有状态。如果,

case .poweredOn:
            btnRefresh.isEnabled = true
            print("central.state is .poweredOn...")

            startScan()
        }

然后我扫描设备。

拿到设备后,我会从扫描设备列表中连接到它,

然后我成功连接到该设备,它会转到 Connect VC。

到这里一切都很好。

但真正的问题开始于

1) 我从 Connect VC to Scan VC 弹出,然后再次弹出到 HOMEVC And

2)然后我再次从Home VC推送到Scan VC

扫描 VC: 这将调用委托(delegate)并将其分配给我的全局 CentralManager,一旦它再次分配委托(delegate),它就会断开之前的连接。 (即使我没有收到任何 didDisconnectPeripheral 电话)

override func viewDidLoad() {
        super.viewDidLoad()

            AppConstants.sharedInstance.centralManager = CBCentralManager(delegate: self, queue: nil) // Here when I come again it disconnects old connection.
    }

不知道是什么问题。我没有收到任何错误。 请帮助...

最佳答案

我认为,由于您在 viewDidLoad 中将 CBCentralManager 重新分配给 AppConstants.sharedInstance.centralManager,因此 CBCentralManager 是被破坏和断开连接。

此外,当它被销毁时,它不会返回任何委托(delegate)回调。

那么你能不能像下面那样尝试只初始化一次 CBCentralManager 并在需要时断开连接?

例子:

override func viewDidLoad() {
        super.viewDidLoad()


        if AppConstants.sharedInstance.centralManager == nil{

            AppConstants.sharedInstance.centralManager = CBCentralManager(delegate: nil, queue: nil)
        }

        AppConstants.sharedInstance.centralManager.delegate = self
    }

关于ios - 核心蓝牙 : CBPeripheral disconnects unknowingly and not getting any call to didDisconnectPeripheral,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53986065/

相关文章:

ios - SideMenuController 不适用于某些 View

Swift - UITextField 填充隐藏清除按钮

osx-mavericks - 终止连接 CBPeripheralManager 端

swift3 - didDiscover外设未调用

ios - 在 XCTest 的 UI 测试中从 TextView 获取文本

ios - Storyboard字段(标签/按钮等)没有出现

ios - 如何在 iOS 应用程序上处理管理员控制的帐户

ios - 如何使用 Magical Record 设置自动迁移核心数据堆栈?

ios - 如何通过 Swift 以编程方式重置蓝牙

javascript - fancybox 下一个和上一个按钮在移动设备中不起作用