In this tutorial, we’ll be discussing and implementing the Timer class. We’ll be developing an iOS Application which runs a Countdown Timer.

Timer

A Timer class is that fires a method at certain intervals.

To create a Timer:

The above timer runs every second. The function passed in the selector gets triggered on every timeInterval.
Setting repeats to false would imply that the timer would be fired just once.
A nonrepeating timer fires once and then invalidates itself automatically.

Timer class has replaced the earlier NSTimer class in Swift.

UserInfo is where we can pass some extra data which can be retrieved from the Timer instance later on.

The data passed inside the UserInfo is a Dictionary.

To stop a Timer we can simply call:

invalidate() stops the Timer from firing again and removes the Timer from the running loop.

Instead of adding a selector function which gets triggered, we can use a closure to run the desired action whenever the Timer is fired.

In the next section, we’ll be creating a Countdown Timer iOS Application with play/pause/reset buttons.
Also, we’ll format the time to show the hours, minutes, seconds properly in the Label.

Project Storyboard

ios-timer-storyboard

Connect the IBOutlet for the Buttons and Label and the IBAction for the Buttons to the ViewController using Control and Drag.

Code

The code for the ViewController.swift is given below:

The formattedTime function is where we format the time to be displayed on the label.
We need to carefully toggle the Pause button text and keep a flag on it to check its current state.
When the Reset Button is clicked, everything is stopped and reset with a new countdown of 6 minutes.

The output of the application in action is given below:

ios timer output

This brings an end to this tutorial. You can download the project from the link below:

By admin

Leave a Reply

%d bloggers like this: