Easy examples to basic swift timer functionality like passing user info, creating repeating swift timers invalidating swift timers and more
Creating Non Repeating Swift Timer
A non-repeating timer can be created in two ways. We will create timers with 1-second durations in examples given below
Passing @objc
function
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: false) // add @objc to function to make it accessible from objective-c code @objc func tick() { print("Hi") }
Using a block
We can also use a block and execute our code in that
let timer3 = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { (timer) in print ("hello") }
Creating a Repeating timer
A repeating timer keeps on firing at fixed intervals till it is invalidated. A swift timer can be made to repeat simply by passing true
in repeats:
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true) // repeats is true
In the case of blocks, we can create a repeating timer in same fashion
let timer3 = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in print ("hello") }
Passing data through timer
We can use userinfo
: to add data to a timer event. This can be any information regarding timer fire. A simple example is
let timer2 = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: ["foo":"val"], repeats: false)
In order to extract the userinfo
: in tik()
we need to accept the timer instance as a parameter and get userinfo
from it. An example is given below
@objc func tick(timer:Timer) { if let info = timer.userInfo as? [String:String] { print(info["foo"]) } }
Invalidating a repeating Swift Timer
A repeating swift timer can be invalidated simply by calling invalidate()
on its instance. This can be achieved either by keeping the reference as shown below
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true) @objc func tick() { print("Hi") } timer.invalidate()
Or from within the function by using timer reference
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(tick), userInfo: nil, repeats: true) @objc func tick(timer:Timer) { print("Hi") if <your condition> { timer.invalidate() } }
If you are using blocks then also you can use the timer reference to invalidate a swift timer.
let timer3 = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in print ("hello") if <your condition> { timer.invalidate() } }
Hope it helps!!!