3

该应用程序在后台,它会在与 BLE 设备断开连接时收到回调,之后应用程序必须等待一段时间(1 分钟)然后执行一些代码。如果屏幕打开,即使在后台,应用程序也会按预期运行。但如果屏幕关闭,则计时器无法正常工作,并且应用程序无法按预期执行。

这是 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

2 回答 2

0

错误已修复,因为应用程序使用位置服务,但我忘记在应用程序处于后台时授予更新位置的权限。

于 2018-05-05T07:52:45.543 回答
0

这里有两点至关重要:

  1. 如果应用程序处于后台状态超过10 分钟,计时器将不起作用。我有一个确切的场景,我必须在后台执行一些操作。我发现 10 分钟后,计时器不起作用。
  2. 设备锁定时定时器不工作。一旦设备被锁定,应用程序会立即暂停。这适用于iOS >= 7.0
于 2018-05-02T08:01:02.353 回答