问题
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 :
- 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.
- 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