Search code examples
swiftnstimer

Swift : Pause and Resume NSTimer


I know this has been posted before, but I'm new to swift and i would like to find help as per my situation. So i need to run a timer, and when the stopMusic() is called(somewhere in my app), i need to pause the timer, then when the playMusic() is called, i need to resume the timer.

Here is what i have:

override func viewDidLoad() {

runFirstDropTimer = NSTimer.scheduledTimerWithTimeInterval(38.2, target: self, selector: "runAnimation", userInfo: nil, repeats: false)

}

func stopMusic() {
//Pause Timer
}

func playMusic() {
//Resume Timer
}

Thank you for any help you can provide!!!


Solution

  • Short answer: You can't. Timers can't be paused.

    Instead you need to record the current time when you start the timer:

    let startTime = NSDate.timeIntervalSinceReferenceDate()
    let interval = 38.2
    //Start your timer 
    runFirstDropTimer = NSTimer.scheduledTimerWithTimeInterval(interval, 
      target: self, 
      selector: "runAnimation", 
      userInfo: nil, 
      repeats: false)
    

    Then, when you want to pause your timer, invalidate it and figure out how much time is left:

    runFirstDropTimer.invalidate()
    let elapsed = NSDate.timeIntervalSinceReferenceDate() - startTime
    let remaining = interval - elapsed
    

    And finally when you want to resume your timer create a new timer with the remaining value.