Show Menu

Do you have a job opening?

Submit your 30 day Job Listing for FREE

In this Swift tutorial we are going to create a basic counter application that utilises the NSTimer class to create a swift timer. This is a great introduction to using NSTimer with Swift.

UPDATE:

This tutorial has been updated for the Latest version of Xcode and Swift. Also, the project files have been fixed to work correctly:

View Tutorial

Jump to:

What is NSTimer?

The NSTimer class can be used to create swift timer objects in your iOS applications. Simply put – a timer. I’m sure you’ve all seen iOS applications that have a similar function to this. Ever wondered how they work? Wondering How NSTimer Works? Well, it works by waiting for a specific interval of time to elapse before it fires. Upon firing it will send a specified message to your swift app target object. For example you can tell your NSTimer object to send a message to a window with instructions to perform an update after a period of time has elapsed, or with this example update a label every second.

So now, are you wondering how to use NSTimer in Swift? Great. I’m about to show you in this tutorial.

Setting up your Xcode Project

Create a new Single View Application is Xcode and name it: NSTimer.

On your Main.storyboard we need to add in a few elements from the Object Library in Xcode. The items we need are:

  • Toolbar
  • Navigation Bar
  • Flexible Space Bar Button Item
  • Bar Button Item x 2
  • UILabel

Toolbar: Drag this to the bottom of your project:

NSTimer Tutorial Toolbar

Next, click on the button that is already there ‘Item’ and head over to the property inspector. We need to change the identifier to Play:

NSTimer Tutorial Property Inspector Play

This should change the ‘Item’ to the widely recognised play icon. So now your toolbar should look like:

NSTimer Tutorial Play button bar

Flexible Space Bar Button Item: This item will space out our bar button items. Drag this item on top of the tool bar that you already have at the bottom of your project:

Swift NSTimer Tutorial Flexible Space Bar Item

Bar Button Item (1): The next item is the Bar Button Item. Drag this item to the bottom left of your toolbar. Like we did before when we changed the identifier to play for the first button we need to do that again but this time change the identifier to Pause. This should now look like this:

NSTimer Tutorial With Swift Pause Button

Navigation Bar: Drag the navigation bar to the op of your view controller. Do not put it right at the top as it will overlap the iPhone Battery icon. Double click the word ‘Title’ and Name it NSTimer Tutorial. This should now look like:

NSTimer Tutorial Navigation Bar In Swift

Bar Button Item (2): Drag another Bar Button Item onto the navigation bar to the right and change the custom identifier to Clear. You can do this by double clicking the word ‘Item‘ and then changing it:

NSTimer Bar Button Clear

UILabel: Finally, the last element. Drag this element onto your View Controller. Preferably in the middle of the project. Go to the Property Inspector and edit the label size, alignment and if you want colour. Next, Double click the UILabel and change the word ‘Label‘ to zero ‘0‘:

NSTimer Bar Button Clear

That’s it for your project setup. Now we can start coding the NSTimer.

NSTimer in Swift

In your Project Navigation Area select the file ViewController.swift. This is the file where we will define and program our NSTimer to use the custom class and perform actions.

In between these lines:


class ViewController : UIViewController {

override func viewDidLoad() {

we need to define our NSTimer. The first variable that we are going to need is a variable called timer of type NSTimer. We do this like:


var timer = NSTimer()

Next we need to define the counter. This will be initially set to zero. So under the above variable declaration we need to declare our variable counter of type integer. Like so:


var counter = 0

On your UILabel in the middle of your storyboard CTRL + Drag to your View Controller file and give it the name of countingLabel:

NSTimer Counting Label UILabel

This should then output the following lines of code into your ViewController.swift file:


@IBOutlet var countingLabel: UILabel!

Do the same for the buttons: Play, Pause and Clear but this time select the connection type of: Action. This should then add these lines of code to your project:


@IBAction func startButton(sender: AnyObject) { }
@IBAction func pauseButton(sender: AnyObject) { }
@IBAction func clearButton(sender: AnyObject) { }

Now we can assign values to the countingLabel. If we go into our viewDidLoad Method. Under super.viewDidLoad() we can add in some basic Swift that will get the variable of counter and assign it to the countingLabel. Hang on a minute! The counter is an integer and the UILabel is a string. we need to make sure we convert the output to string before passing it to the Label. This can simply be done by wrapping it in String(*):


countingLabel.text = String(counter)

Start NSTimer

In out IBAction startButton we need to add in:


timer = NSTimer.scheduledTimerWithTimeInterval(TIME_INCREMENT, target:self, selector: Selector("FUNCTION"), userInfo: nil, repeats: BOOL)

What this line will do is assign a new instance of NSTimer to the variable timer that we created earlier. As you can see in the line there are a few things I have added in in capitals; TIME_INCREMENT,FUNCTION,BOOL. Here are those parameters and what we’re going to do with them.

Parameter Usage
TIME_INCREMENT The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead. We are going to set this to 1.
FUNCTION A function that we will create that will be triggered on the time. We are going to call this updateCounter.
BOOL If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires. We are going to set this to yes

so now, this line should look like:


timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)

The next thing we need to do is create the function that we declared here: Selector(“updateCounter”) and update the counter integer by a value of 1. We do this similar to the way that we defined in the viewDidLoad however we need to add ++ to the counter as this will add 1 every time it is called. Which as you remember we told the NSTimer.scheduledTimerWithTimeInterval to call it every second. Like so:


func updateCounter() {
    countingLabel.text = String(counter++)
}

Run your app, Press start and see the magic and simplicity of coding NSTimer with Swift

Pause/Stop NSTimer

This class comes with the method invalidate() Which is the perfect way to stop / pause your NSTimer. In the IBAction that we created for the pause button we simply need to add in one line of code:


@IBAction func pauseButton(sender: AnyObject) {
    timer.invalidate()
}

Run your app, Press the pause button and notice how easy it is to use NSTimer with Swift

Clear the NSTimer Counter

Clearing the NSTimer is a little different as we need to do several things when the button is pressed:

  • Stop NSTimer from firing
  • Reset the counter
  • Clear the countingLabel on the View

Note: These must be done in the above order.

They are all simple to do, your final IBAction should look like:


@IBAction func clearButton(sender: AnyObject) {
    timer.invalidate()
    counter = 0
    countingLabel.text = String(counter)
}

There you have it. Run your app. and Voila. As you can see you have created a basic counting app using NSTimer and Swift.

Subclassing NSTimer

I thought that I would just quickly mentioned subclassing with NSTimer.
What is subclassing? Well.. A class can inherit all sorts from another class like methods and properties and many more characteristics. It is this, when one class inherits from another class that it is known as subclassing.

It is recommended in the Apple Documentation for NSTimer that you do not try to subclass this class.

Summary

In this NSTimer Swift Tutorial we have learned how to use NSTimer to call a custom function at a certain time interval so what we can create a swift timer application. We have learned how to pause, start and clear the NSTimer in Swift. We have also learned how to deal with integers and strings.

Download the files

There have been some issues with the project files for this tutorial. Please check out the New updated version of this tutorial for Swift 2 here

Swift Timer Tutorial

If you liked this tutorial, and want to carry on your Swift Application Development further than how to create a Swift Timer, check out our awesome collection of Swift Tutorials

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


iOS-Blog Admin Team

Written by:

We're here to help.

Comments

comments