简体   繁体   中英

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

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!)
} 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM