Swift timer example – Repeat action

This tutorial will go through how to make an action repeat itself after a specific interval of time as a swift timer example.

This code is written and verified on macbook pro using:

XCode 8.2

Swift 3.0.2

MacOS Sierra 10.12.2

How to make an action repeat using Timer in Swift

Lets understand swift 3 timer with swift timer example.

Steps for swift 3 timer example are as follows.

1. Initialise a custom variable to hold the Timer object

We initialize the custom variable to hold the built in Timer object like this inside our class code (outside the methods of course, just after the opening tag for our AppDelegate class, inside AppDelegate.swift file):

    var customTimer: Timer!

Remember not to name this variable “Timer” or it can cause confusion later.

2. Add code in applicationDidFinishLaunching method

We need to modify the variable now. However we can do it after the application has launched. So we add this inside the applicationDidFinishLaunching method.

Make sure to change the ourCustomMethod in this code to your custom method name which you want to be called and run once the timer interval hits. 

We can change the swift timer delay by changing timeInterval in following code.

        customTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ourCustomMethod(sender:)), userInfo: nil, repeats: true)

If your method don’t have any specific sender then we can add Any as sender in our method declaration. The code becomes:

        customTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ourCustomMethod), userInfo: nil, repeats: true)

How to invalidate the timer

We can invalidate the timer when we need. Especially when the view is about to disappear by using this code.

customTimer.invalidate()

The complete code becomes

    // initialize the variable to hold Timer object
    var customTimer: Timer!

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        // Insert code here to initialize your application

        // timer code
        customTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ourCustomMethod(sender:)), userInfo: nil, repeats: true)

    }

    func ourCustomMethod(sender: NSStatusBarButton) {

        // our custom code here

    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application        

       customTimer.invalidate()

    }

Hopefully this would help you implement a swift 3 timer in your cocoa app using xcode. Let me know if you have any suggestions, queries or corrections to this swift timer example.

Leave a Reply

Your email address will not be published.