1

This is a bit of a common question but most answers don't seem to work. I have a timer in my app that and I can start and re-start the timer easily. I am trying to pause and resume the timer but for now resuming only continues the timer from a timer that's greater than the one I resumed it at. Which probably means it continues counting in the background. This is my code :

//Timer Variables
var startTime = NSTimeInterval()
var timer = NSTimer()
var isTiming = Bool()
var isPaused = Bool()

func updatedTimer() {

        let currentTime = NSDate.timeIntervalSinceReferenceDate()
        var elapsedTime: NSTimeInterval = currentTime - startTime
        let minutes = UInt8(elapsedTime / 60.0)

        elapsedTime -= (NSTimeInterval(minutes) * 60)
        let seconds = UInt8(elapsedTime)

        elapsedTime -= NSTimeInterval(seconds)

        let strMinutes = String(format: "%02d", minutes)
        let strSeconds = String(format: "%02d", seconds)

        workoutTime.text = "\(strMinutes) : \(strSeconds)"

    }


    @IBAction func startButtonTapped(sender: AnyObject) {

        if !timer.valid {

            timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
            startTime = NSDate.timeIntervalSinceReferenceDate()
        }

        isTiming = true
        isPaused = false

    }


    @IBAction func pauseAndContinueButtonTapped(sender: AnyObject) {

        if isTiming == true && isPaused == false {

            timer.invalidate() //Stop the Timer
            isPaused = true //isPaused
            isTiming = false //Stopped Timing
            pauseButton.setTitle("RESUME", forState: UIControlState.Normal) //Set Button to Continue state


            print(startTime)


        } else if isTiming == false && isPaused == true {

            if !timer.valid {

                timer.invalidate()
                //timer = nil

                timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer),     userInfo: nil, repeats: true)

            }


            isPaused = false
            isTiming = true
            pauseButton.setTitle("PAUSE", forState: UIControlState.Normal) //Set Button to Continue state

        }

    }
1
  • Using timeIntervalSinceReferenceDate will have problems if the user changes the system time. It is better to use a time value which is independent of that time like CACurrentMediaTime().
    – ThomasW
    Nov 18, 2021 at 6:44

2 Answers 2

6

I have a custom timer application and dealt with the same issue. There are many ways to address this. You may want to track pausedTime like you do elapsedTime and subtract that from your other variables. This gives you some flexibility as well to show totalTime vs. elapsedTime, etc... My function is quite a bit different, so I retrofitted it to your setup.

Basically, pausing is different because you can pause/resume multiple times. So you need to track previous pauses, and current pause state and subtract from elapsed time (or total time, or whatever you want).

I tested this code and it worked. Give it a try and let me know:

import UIKit

class TimedWorkoutViewController: UIViewController {

  @IBOutlet weak var pauseButton: UIButton!
  @IBOutlet weak var startButton: UIButton!

  var startTime = NSTimeInterval()
  var timer = NSTimer()
  var isTiming = Bool()
  var isPaused = Bool()
  var pausedTime: NSDate?   //track the time current pause started
  var pausedIntervals = [NSTimeInterval]()   //track previous pauses

  override func viewDidLoad() {
    super.viewDidLoad()

  }

  func updatedTimer() {
    let currentTime = NSDate.timeIntervalSinceReferenceDate()
    var pausedSeconds = pausedIntervals.reduce(0) { $0 + $1 }   //calculate total time timer was previously paused
    if let pausedTime = pausedTime {
      pausedSeconds += NSDate().timeIntervalSinceDate(pausedTime)  //add current pause if paused
    }
    var elapsedTime: NSTimeInterval = currentTime - startTime - pausedSeconds  //subtract time paused
    let minutes = Int(elapsedTime / 60.0)

    elapsedTime -= (NSTimeInterval(minutes) * 60)
    let seconds = Int(elapsedTime)

    elapsedTime -= NSTimeInterval(seconds)

    let strMinutes = String(format: "%02d", minutes)
    let strSeconds = String(format: "%02d", seconds)

    workoutTime.text = "\(strMinutes) : \(strSeconds)"
  }


  @IBAction func startButtonTapped(sender: AnyObject) {

    if !timer.valid {

      timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
      startTime = NSDate.timeIntervalSinceReferenceDate()
    }

    isTiming = true
    isPaused = false
    pausedIntervals = []  //reset the pausedTimeCollector on new workout
  }


  @IBAction func pauseAndContinueButtonTapped(sender: AnyObject) {

    if isTiming == true && isPaused == false {

      timer.invalidate() //Stop the Timer
      isPaused = true //isPaused
      isTiming = false //Stopped Timing
      pausedTime = NSDate() //asuuming you are starting a brand new workout timer
      pauseButton.setTitle("RESUME", forState: UIControlState.Normal) //Set Button to Continue state

    } else if isTiming == false && isPaused == true {

      let pausedSeconds = NSDate().timeIntervalSinceDate(pausedTime!)  //get time paused
      pausedIntervals.append(pausedSeconds)  // add to paused time collector
      pausedTime = nil   //clear current paused state

      if !timer.valid {

        timer.invalidate()
        //timer = nil

        timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer),     userInfo: nil, repeats: true)

      }


      isPaused = false
      isTiming = true
      pauseButton.setTitle("PAUSE", forState: UIControlState.Normal) //Set Button to Continue state

    }

  }
}
3
  • Awesome. Worked perfectly. Thanks a lot.
    – Gugulethu
    Jun 8, 2016 at 9:30
  • So, on the line that says pausedIntervals.append( pausedSeconds ) I get the following error: Cannot convert value of type '(Date) -> TimeInterval' to expected argument type 'TimeInterval' (aka 'Double') Any idea why? Several Google searches and still nothing.
    – mnearents
    Mar 23, 2017 at 6:56
  • Figured it out. I am using Date instead of NSDate. I was using Date.timeIntervalSinceDate(pausedTime!) instead of `Date().timeIntervalSinceDate(pausedTime!)'
    – mnearents
    Mar 23, 2017 at 7:09
6

Here is some code I once used to track time

class TimeTracker : NSObject {
private var startTime:NSTimeInterval?
private var timer:NSTimer?
private var elapsedTime = 0.0
private var pausedTimeDifference = 0.0
private var timeUserPaused = 0.0
var delegate:TimeTrackerDelegate?

func setTimer(timer:NSTimer){
    self.timer = timer
}

func isPaused() -> Bool {
    return !timer!.valid
}

func start(){
    if startTime == nil {
        startTime = NSDate.timeIntervalSinceReferenceDate()
        newTimer()
    }
}

func pause(){
    timer!.invalidate()
    timeUserPaused = NSDate.timeIntervalSinceReferenceDate()
}

func resume(){
    pausedTimeDifference += NSDate.timeIntervalSinceReferenceDate() - timeUserPaused;
    newTimer()
}

func handleTimer(){
    let currentTime = NSDate.timeIntervalSinceReferenceDate()
    elapsedTime = currentTime - pausedTimeDifference - startTime!
    delegate!.handleTime(elapsedTime)
}

func reset(){
    pausedTimeDifference = 0.0
    timeUserPaused = 0.0
    startTime = NSDate.timeIntervalSinceReferenceDate()
    newTimer()
}

private func newTimer(){
    timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target:self ,  selector: "handleTimer", userInfo: nil, repeats: true)
}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.