【问题标题】:Swift 3: How to scan for peripherals in background?Swift 3:如何在后台扫描外围设备?
【发布时间】:2016-10-13 14:44:15
【问题描述】:

这是我的场景:

我连接了两个外围设备,将我的应用程序置于后台模式并开始使用外围设备,直到它们与我的应用程序失去连接。回来时,它们在到达时不再连接。

当我在应用程序在前台运行时执行相同的实验时,没有发生任何问题 - 将外围设备靠近 iPhone 会导致重新连接。

但是,我在控制台中看到,当外围设备失去连接时,正在调用 DidDisconnectPeripheral 方法。问题是这个方法内部没有调用扫描

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    numberOfTagsSending = numberOfTagsSending - 1
    numberOfConnectedTags = numberOfConnectedTags - 1
    print("Tag was disconnected. Start scanning.")

    synchronizer.alreadySynced = false

    central.scanForPeripherals(withServices: arrayOfServices, options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])
}

我阅读了this 的答案,并以完全相同的方式进行了所有操作,不幸的是它不起作用。

提前致谢

【问题讨论】:

  • 你试过在Application: didEnterBackground调用这个函数吗?
  • 好吧,老实说我没有。但是我从来没有找到任何我应该从 AppDelegate 显式调用它的信息
  • 尝试一下,看看它是否在后台工作,如果没有,那么你的central.scanForPeripherals()方法一定有问题,因为你的问题没有正确设置。
  • @KSigWyatt 这也不起作用
  • 无需扫描。只需在didDisconnectPeripheral 中调用connect,当它再次可见时,iOS 将自动重新连接到外围设备。什么对象持有您的 CBCentralManager 实例?是单例吗?

标签: ios swift core-bluetooth


【解决方案1】:

拥有CBPeripheral 实例后,您无需再次发现它。您可以简单地连接到它;如果外围设备当前不在范围内,那么一旦外围设备进入范围,iOS 将自动连接并调用您的 didConnectPeripheral 委托方法。

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    numberOfTagsSending = numberOfTagsSending - 1
    numberOfConnectedTags = numberOfConnectedTags - 1

    central.connect(peripheral)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多