NSTimer in Swift
Our aim is to create a counter application, and it will make use of the Swift NSTimer class. This class can be used to create a timer in iOS 8 applications. It functions by waiting for a specific interval of time to elapse so that it can fire.
Once it fires, a message is always to the Swift object which is targeted. A good example is the scheduling of updates, whereby the timer can be used to trigger this at a specific time. To create such an app, the project needs to be set up in a specific manner.
Project Setup
Create a new application (Single View) and give it a name of your choice. We then need to add some elements to the Main.storyboard. These will be obtained from the object Library in Xcode. These elements include a navigation bar, toolbar, UILabel, Bar Button,Item x 2, and a flexible Space Bar Button Item.
Adding the Toolbar
Begin by dragging this to the project’s bottom:
Click on the “Item” button and go to the property inspector. Choose play:
The “Item” will change to a play icon, and the toolbar will be as follows:
Adding the Flexible Space Bar Button Item
The purpose of this is to space out the bar button items. On top of the toolbar located at the project’s bottom part, drag this item:
Item 1 of Bar Button
Drag this to the bottom and left of your toolbar. It should look as follows:
Navigation Bar
On top of the view controller, drag the navigation bar. Avoid overlapping the iPhone battery by not placing the navigation bar right at the top. Double click the word “Title,” and rename it to something else of your choice. In my case, I will rename it to “NSTimer Tutorial” so it should look as follows:
Item 2 of Bar Button
Add another bar button on the navigation by dragging it. Place it to the right. Double click on the “Item” and change it to “Clear.”

UILabel
Onto the view controller, drag this item. Place it at the middle of the project. From the property inspector, edit the label alignment, size, and color (optional). Double click on the word “Label,” and change it to 0 (zero).
The interface is now set up. The next thing is to start coding so as to add the necessary functionality to the timer.
Coding the timer
Select the file ViewController.swift from the navigation area of the project. This is where coding should be done to add functionality to the NSTimer. To define the timer, we need to do this between the following lines of code:
|
1
2
|
class ViewController : UIViewController {
override func viewDidLoad() {
|
We define our first variable “tm” for timer which is of type NSTimer as follows:
|
1
|
var tm = NSTimer()
|
Above the declaration above, we should define the counter and initialize it to 0 as follows:
|
1
|
var counter= 0
|
At the middle of the storyboard and on the UILabel, press the Ctrl key and drag to your view controller file. Name it CountingLabel.
Check the ViewController.swift file to see if it has the following code:
|
1
|
@IBOutlet var countingLabel: UILabel!
|
Repeat the same procedure for the other buttons, but this time, make sure you choose the connection type “Action.” After doing that, the following code should be added to your project:
|
1
2
3
4
5
|
@IBAction func startButton(sender: AnyObject) { }
@IBAction func pauseButton(sender: AnyObject) { }
@IBAction func clearButton(sender: AnyObject) { }
|
Values can then be added to the CountingLabel. Note that the UILabel is a string, whereas the counter is an integer. The output must be converted to a string before adding it to the label. This can be done as follows:
|
1
|
countingLabel.text = String(counter)
|
It’s time to start the timer. This can be done by adding this functionality to the startButton as follows:
|
1
|
tm = NSTimer.scheduledTimerWithTimeInterval(TIME_INCREMENT, target:self, selector: Selector("FUNCTION"), userInfo: nil, repeats: BOOL)
|
Remember that we created variable tm earlier on, and what we done in this case is assigning a new instance of NSTimer to this. Note that we have added some new things as explained below:
- TIME_INCREMENT- specifies the number of seconds after which the timer fires. We will set this one to 1.
- FUNCTION- this is a function to be created, and it will be triggered when the firing time is reached.
- BOOL- if the value of this is set to “YES,” it will keep on rescheduling itself until it is invalidated. After firing, the timer will be invalidated if this value is set to “NO.”
The above line of code then becomes:
|
1
|
tm = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("counterUpdator"), userInfo: nil, repeats: true)
|
We have declared a function in the above line of code. We need to create it and use it for the purpose of incrementing the value of the counter by 1. Assuming that you know the increment operator, that is, ++, let us use this, and it will increment this value by 1. This will happen every time this function is called. This will then become:
|
1
|
Func counterUpdator() { countingLabel.text = String(counter++) }
|
You can now run your app. Once you click on start, you will realize how much you have achieved with less coding.
Stopping the NSTimer
The method Invalidate() is used to pause or stop the NSTimer. We need to add some functionality to the IBAction of the pause button as shown below:
|
1
2
3
|
@IBAction func stopButton(sender: AnyObject) {
tm.invalidate()
}
|
Now you can play around with the timer by starting it and pausing it.
Clearing the NSTimer
For us to clear the counter, the following needs to be done:
- Pause the NSTimer from firing.
- Reset the counter to normal.
- Clear the countingLabel.
Note that the above order must be adhered to, otherwise the objective will not be achieved. The following should be the appearance of the IBAction of the clearButton:
|
1
2
3
4
5
|
@IBAction func clearButton(sender: AnyObject) {
tm.invalidate()
counter = 0
countingLabel.text = String(counter)
}
|
You can now run your app. Every feature that we wanted has worked, so we are done. The timer has been created with Swift and NSTimer. This shows how much Swift can be used to develop amazing apps for iOS 8 devices. More so, using integers and strings should not be a =n issue to you now as you have learned how to use them.


























