Countdown Timer in Swift 5 for iOS

Photo by Jon Tyson on Unsplash

This article explains how to create a Countdown Timer in Swift 5 for iOS.

Goal

Create StopWatch with Start, Pause, Stop functions. Show time in hh:MM:ss format.

Countdown Timer in Swift 5 for iOS
Countdown Timer in Swift 5 for iOS

Timer

First of all, we will use repeating
scheduledTimer(withTimeInterval:repeats:block:) method (of the Timer) that as the documentation says:

Creates a timer and schedules it on the current run loop in the default mode.

Briefly, the timer fires and executes a block when interval (in seconds) has elapsed.

Initialize timer and save in the property for invalidating if needed later.

Approaches overview

I will explain why incrementing approach (when you create variable and increment it every second when timer block is called) is not the best solution.

Another way is to calculate the difference between current and start counting time using TimeIntervals.

If you want to be able to Pause the timer, you should also store last pause time and consider previous pauses offset (if there were).

Despite incrementer takes less code, this approach is better because:

  1. High accuracy (due to millisecond sensitivity). Date timeIntervalSince1970 takes milliseconds into account that you wound’t get using incrementer.
  2. Timer block can be delayed (so incrementer will show wrong time)
  3. Because timer won’t get fired in the background mode (to avoid battery draining), idle time will be taken into account when the application goes to the foreground mode again.

Countdown timer logic

Obviously, you can play with fromDate and toDate variables depending on the goal you have (such as reverse timers or countdown).

Displaying result

Formatting Hours, Minutes, Seconds

To display the time in needed format, let’s calculate hours, minutes and seconds.

Pause and resume

stopwatch.toggle()

Reset

stopwatch.stop()


Important! Please be sure to invalidate the timer when the view disappears (to avoid memory leaks).

Fin

This timer implementation may be used to solve different problems. You may build countdown, stopwatch, alarm and much more.

Personally I used it to build reading log timer in Reado app which help users to track time they spent while reading their books.

Countdown Timer in Swift 5 for iOS
Book tracker app with reading session logger

Want to see it live? Run Reado app and open reading logger.


Thanks for the reading!
I hope you find out more about how to create a StopWatch or Countdown Timer in Swift 5 for iOS.

For lazy people like me I just leave source on Github here.

Check my previous articles:

If you have any questions or spot any errors please let me know.

Written with ❤️ by Rita