Search code examples
swiftnstimer

Swift. Make a NSTimer keep running after the app is closed


Okay I am building an app where you have 6 lives, when you die you have to wait 2 minutes to get new lives, heres what I have until now:

var timeLeft = 120
var countDownTime = NSTimer()

func died() {
    countDownTime = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: ("updateTimer"), userInfo: nil, repeats: true)
}

func updateTimer() {
    timeLeft--
    if timeLeft == 0 {
        stopTimer()
    }
}

func stopTimer() {
    countDownTime.invalidate()
    timeLeft = 120
}

My question is how do i keep this timer running, so when i close and open my app, the timer has kept running?

sorry if this is a duplicate question, I just haven't been able to get an answer to my question.


Solution

  • You may want to save the timer start timestamp into NSUserDefaults:

    If the user leaves the app. When entering, in your AppDelegate or InitialViewController you can check if the elapsed time is bigger than 2 minutes and proceed or to show the wait screen to the user.