当屏幕关闭/设备在iOS中被锁定时,计时器未运行

问题描述 投票:3回答:2

该应用程序处于后台,它在与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!)
} 
ios timer uibackgroundtask screen-off ios-background-mode
2个回答
0
投票

这里有两点至关重要:

  1. 如果应用程序处于后台状态超过10分钟,则计时器不起作用。我有一个确切的场景,我必须在后台执行一些操作。我发现10分钟后,计时器无法正常工作。
  2. 设备锁定时,计时器不起作用。设备锁定后,应用会立即暂停。这适用于iOS> = 7.0

0
投票

Bug是固定的,因为应用程序使用位置服务,但我忘了在应用程序处于后台时允许更新位置。

© www.soinside.com 2019 - 2024. All rights reserved.