0

I have the following in my touchesBegan function in my GameScene so that the timer only starts when the user touches a certain sprite:

let start = SKAction.runBlock({
    NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "printDuration:", userInfo: NSDate(), repeats: true)
})

tapToStartNode.runAction(start)

and the following function:

func printDuration(timer: NSTimer) {
    if self.view?.paused == false {
        guard let userInfo = timer.userInfo else {
            return
        }
        guard let startDate = userInfo as? NSDate else {
            return
        }
        let duration = NSDate().timeIntervalSinceDate(startDate)
        currentTime = NSDate().timeIntervalSinceDate(startDate)
        currentTimeValueLabel.text = "\(NSString(format:"%3.2f", duration))"
    }
}

However, when applicationDidEnterBackground or applicationWillResignActive the timer is not paused and continues to run when the app is in the backgorund. How do I make it stop?

Chris Slowik
  • 2,859
  • 1
  • 14
  • 27
spigen
  • 81
  • 1
  • 7
  • 1
    Possible duplicate of [How can I programmatically pause an NSTimer?](http://stackoverflow.com/questions/347219/how-can-i-programmatically-pause-an-nstimer) – nhgrif Feb 24 '16 at 01:36
  • It isn't that the timer isnt paused, it is that you are calculating elapsed time based on a start time. You need to note the time when the app goes into the background and record the current elapsed time. Then, when you re-enter the foreground note the new start time. The elapsed time will be now-startTime+previousElapsedTime – Paulw11 Feb 24 '16 at 01:48
  • Would I have to do that in the app delegate and then pass the values to my game scene? – spigen Feb 24 '16 at 01:59
  • 1
    you shouldnt be using an NSTimer in a spritekit game at all. you should be using SKAction. SKAction pauses itself when the game is paused and you dont need to manage it. If you have logic involved then you need to be keeping track of time in your update method. using NSTimer will give you an unnecessary headache.. – hamobi Feb 28 '16 at 13:39

1 Answers1

1

Here a tips you can use for your problem

You can use func applicationDidEnterBackground(_ application: UIApplication) or func applicationWillResignActive(_ application: UIApplication) on AppDelegate

Access your controller by initialize rootViewController example :

let vc = self.window?.rootViewController as? ViewController

Then you can access your function (make sure function is on public state)

vc.pauseTimer() (customize based on your situation)

Hope it will be helpful

Wendy Liga
  • 634
  • 5
  • 12