Continue countdown timer when app is running in background/suspended

前端 未结 4 871
灰色年华
灰色年华 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:18

    What I suggest is cancel the timer and store a NSDate when the app goes to the background. You can use this notification to detect the app going to the background:

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "pauseApp", name: UIApplicationDidEnterBackgroundNotification, object: nil)
    

    Then cancel the timer and store the date:

    func pauseApp(){
        self.stop() //invalidate timer
        self.currentBackgroundDate = NSDate()
    }
    

    Use this notification to detect the user coming back:

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "startApp", name: UIApplicationDidBecomeActiveNotification, object: nil)
    

    Then calculate the difference from the stored date to the current date, update your counter and start the timer again:

    func startApp(){
        let difference = self.currentBackgroundDate.timeIntervalSinceDate(NSDate())
        self.handler(difference) //update difference
        self.start() //start timer
    }
    

提交回复
热议问题