#14: NSTimer with Swift 3

Timer

Timers are used to execute a method after a configured delay expressed in seconds, in Swift 3 the NSTimer class has been renamed as Timer.

We’ll declare a Timer that will call the after5Sec function of the Handler object after 5 seconds:


class Handler : NSObject{
    func after5Sec(timer:Timer){
        print("Called after 5 seconds!")
        if let userInfo = timer.userInfo as? [String:String] {
            print("Invoked with param: " + userInfo["param1"]!)
        }
        timer.invalidate() //Always invalidate the current timer
    }
}

let h = Handler()

Now that we’ve created a reference to the handler, we can setup the timer. Let’s include a simple userInfo dictionary to see how parameters can be passed to the handler:


let timer = Timer.scheduledTimer(timeInterval: 5,
                                 target: h,
                                 selector: #selector(Handler.after5Sec(timer:)),
                                 userInfo: ["param1":"value1"],
                                 repeats: false)

We can stop the time before it fires using the invalidate method:


timer.invalidate()

Did you like this article? Let me know on Twitter or subscribe for updates!


I'm also on Twitter and GitHub.

Subscribe via RSS or email.