Continue countdown timer when app is running in background/suspended

前端 未结 4 892
灰色年华
灰色年华 2021-01-01 04:32

I have a functional countdown timer.

The problem is that I need to continue the countdown when the user puts the app in the background. Or suspends the app? I am no

4条回答
  •  再見小時候
    2021-01-01 05:09

    Be sure that you turn on the background mode and set needed values in xCode. It is strange, but even if background mode is turned off, this code works. It seems to be work any timers after setting application.beginBackgroundTask {} in AppDelegate.

    I use this code:

    In AppDelegate add code below:

    func applicationDidEnterBackground(_ application: UIApplication) {
    
        application.beginBackgroundTask {} // allows to run background tasks
    }
    

    And call method below where you want.

    func registerBackgroundTask() {
        DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime.now() + 5, qos: .background) {
                print("fasdf")
            }
    }
    

提交回复
热议问题