ios - Swift 3 CoreBluetooth后台数据接收

标签 ios swift bluetooth

我正在尝试从 Arduino 接收一些数据,当我按下按钮时它会发出一些数据。

现在我注意到它在一段时间后没有收到。我没有杀 应用程序还没有。怎么会?我已经添加了

<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
    <string>bluetooth-peripheral</string>
    <string>external-accessory</string>
</array>

我的设备都已配对。

编辑:

我正在尝试做与 Tile App 相同的事情,它在那里工作得很好。

编辑 2:

我像这样实例化我的经理:

centralManager = CBCentralManager(delegate:self, queue:nil)

最佳答案

您需要通过传递您的恢复 key 标识符的选项参数来初始化您的 CBCentralManager。

let central = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: "yourkey"])

“您的 key ” 可以是您想要的任何内容,这对您了解您的应用已被唤醒以处理 BLE 消息很有用。如果应用程序被系统杀死,当一个新的 BLE 消息将导致它在你的应用程序委托(delegate) didFinish 中复活时,启动这个键将在选项参数中传递。

要使其正常工作,您必须实现委托(delegate)方法

optional public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any])

这将在应用程序被系统杀死(或崩溃......顺便说一下,不是由用户)的情况下被调用,以通知你一个新的 BLE 事件发生了。在 will restore state 字典中,您将拥有恢复 BLE session 所需的所有信息。

Here你会发现所有 apple 的建议都在后台使用 BLE。

请记住,如果用户执行任何导致连接断开的操作(例如应用程序终止、蓝牙禁用),与您的外围设备的连接将始终被切断。 iOS 将继续唤醒/恢复您的应用程序,以防崩溃、应用程序在后台运行然后被系统杀死。

将导致应用程序被唤醒的事件是来自已注册通知特性的通知、新外设的发现、特性的读取。 (基本上是 CoreBluetooth 委托(delegate)的任何回调)

请记住,在后台进行扫描操作有局限性。

来自之前链接的苹果文档:

Although you can perform many Bluetooth-related tasks while your app is in the background, keep in mind that scanning for peripherals while your app is in the background operates differently than when your app is in the foreground. In particular, when your app is scanning for device while in the background:

  • The CBCentralManagerScanOptionAllowDuplicatesKey scan option key is ignored, and multiple discoveries of an advertising peripheral are coalesced into a single discovery event.
  • If all apps that are scanning for peripherals are in the background, the interval at which your central device scans for advertising packets increases. As a result, it may take longer to discover an advertising peripheral.

快乐编码。

关于ios - Swift 3 CoreBluetooth后台数据接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44943855/

相关文章:

ios - 无法从 Crashlytics 重置 firebase 链接

ios - 更新pod内部库

安卓。连接蓝牙设备

android - Bluetooth LE Android 平板电脑无法与 Lego Boost Move Hub 连接

ios - 使用未声明的类型 'XCTestCaseEntry'

ios - 如果在另一个表更新后调用得太快,tableView.reloadRows 会闪烁

html - 本地 webapp 可以在 iOS 上运行吗?

swift - 分段 Controller

objective-c - 我应该为 iOS 学习 Swift 还是 Objective C

java - 如何在android中分离通过蓝牙接收的数据