Timers not running when screen is turned off / device is locked in iOS

☆樱花仙子☆ 提交于 2020-01-04 02:56:10

问题


The app is in the background and it receives a callback upon disconnection with the BLE device, after which the app has to wait for sometime(1minute) and then execute some piece of code. The app behaves as expected even when in the background if the screen is turned on. But if the screen is turned off then the timer is not working and the app is not executing as expected.

This is the code in AppDelegate to start a timer in background:

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
}

When disconnected from the BLE device, I start the timer by registering to background task:

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

回答1:


Two points are vital here :

  1. Timer doesn't work if the app is in background state for more than 10 minutes. I had an exact scenario where I had to perform some action in background. I found out that after 10 minutes, timer didn't work.
  2. Timers do not work when the device is locked. App gets suspended immediately once the device is locked. This is for iOS >= 7.0



回答2:


Bug is fixed its because app using location services but I forgot to given permission to update location when app is in background.



来源:https://stackoverflow.com/questions/50129279/timers-not-running-when-screen-is-turned-off-device-is-locked-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!