2

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.

xoudini
  • 7,001
  • 5
  • 23
  • 37
Benja0906
  • 1,437
  • 2
  • 15
  • 25
  • by opening app, you mean open app from terminated state or background state, and also explain closing app? – Breek Feb 04 '16 at 19:17
  • this may help: http://stackoverflow.com/questions/34862160/make-timer-run-on-background-ios-for-more-than-3-minutes – Dan Beaulieu Feb 04 '16 at 19:18
  • Persistent Storage? When the player dies, store the datetime. Whenever they player tries to restart the game, you need to make sure two minutes have passed since the time you stored. – AgRizzo Feb 04 '16 at 19:26

2 Answers2

2

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.

Hugo Alonso
  • 6,684
  • 2
  • 34
  • 65
0

I guess you want NSTimer run correct when your app run background. Is it correct?

When app run background then NSTimer only run correct about 3 minutes (from IOS7) or 10 minutes (before IOS7). So if you want NSTimer run correct when app run background then you need provide a process run background (Ex: Play audio).

How to run background Audio, you can refer this link: http://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial

Regards.

chaunv
  • 833
  • 6
  • 15