This article explains how to create a Countdown Timer in Swift 5 for iOS.
Create StopWatch with Start, Pause, Stop functions. Show time in hh:MM:ss format.
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.
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:
- High accuracy (due to millisecond sensitivity). Date timeIntervalSince1970 takes milliseconds into account that you wound’t get using incrementer.
- Timer block can be delayed (so incrementer will show wrong time)
- 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).
Formatting Hours, Minutes, Seconds
To display the time in needed format, let’s calculate hours, minutes and seconds.
Pause and resume
Important! Please be sure to invalidate the timer when the view disappears (to avoid memory leaks).
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.
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.
Check my previous articles:
- Handling Internet Connection reachability in iOS (Swift 5)
- Swift tutorial: How to create own xCode File Template for iOS and MacOS
- iOS Localization Advices (Swift 5)
If you have any questions or spot any errors please let me know.
Written with ❤️ by Rita