1

该应用程序处于后台,并在与 BLE 设备断开连接时收到回调,之后应用程序必须等待一段时间(1 分钟)然后执行一些代码。该应用程序即使在后台运行并且只是连接到系统(Mac、Windows 或 Ubuntu)时也能按预期运行,但在其他情况下则不然。此行为仅在 iOS 11.3 上可见,在 10.3 上不可见。

当app处于后台,并且在BLE设备断开连接时收到回调,app注册一个定时器为1分钟的后台任务,之后会进行一定的api调用。

以下是我的观察:

  1. 如果设备连接到系统,所有后台任务和 api 调用都会优雅地进行。
  2. 如果设备未连接到系统,则后台任务和 api 调用不会在 iOS 11.3 中执行,但在 10.3 上运行良好(如果计时器超过 10 秒在 10.3 上运行良好,但在 11.3 上运行良好)
  3. 当我进行无线调试时,与 iPhone 的连接会在几秒钟后自动丢失(>10)。(在 11.3 中观察到此行为)
  4. 当计时器小于或等于 10 秒时,该应用程序在所有版本上都能完美运行,即使它没有连接到任何系统。

这是 AppDelegate 中用于在后台启动计时器的代码:

func startTimerWith(timeInterval: TimeInterval) {
    registerBackgroundTask()
    timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false, block: { (timer) in
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Time"), object: nil)
        self.endBackgroundTask()
    })
}

func registerBackgroundTask() {
    backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        self.endBackgroundTask()
    })
}

func endBackgroundTask() {
    print("Background task ended.")
    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
    timer?.invalidate()
    timer = nil
}

当与 BLE 设备断开连接时,我通过注册到后台任务来启动计时器:

func disconnected(_ peripheral: CBPeripheral, with error: Error?) {
    print("DISCONNECTED!!!")
    AppDelegate.sharedApp().startTimerWith(timeInterval: TimeInterval(TIME))
    BLEDeviceHandler.sharedInstance.handleBLEDevice(connectedPeripheral!)
}   
4

0 回答 0