When developing iOS apps, it's common to have tasks that need to be performed repeatedly or with a delay. One way to accomplish this is by using the Timer class provided by Swift.
The Timer class can be used to schedule a task to be performed after a certain time interval or repeatedly with a fixed time interval. In this article, we'll go over some examples of how to use the Timer class in Swift.
To use the Timer class, you first need to create an instance of it and specify the time interval and the target method to be executed. Here's an example:
1let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
This creates a new timer that will fire every second and call the updateTimer
method on self
. The userInfo
parameter can be used to pass additional information to the target method if needed.
Note that the updateTimer
method needs to be marked with the @objc
attribute since it will be called using Objective-C.
1@objc func updateTimer() {2 // Code to be executed3}
To stop the timer, you can call its invalidate
method:
1timer.invalidate()
If you need to perform a task repeatedly, you can set the repeats
parameter to true
when creating the timer. Here's an example of how to use a timer to update a label every second:
1var counter = 02
3@objc func updateLabel() {4 counter += 15 myLabel.text = "\(counter)"6}7
8let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateLabel), userInfo: nil, repeats: true)
If you need to perform a task after a certain delay, you can set the timeInterval
parameter to the desired delay and the repeats
parameter to false
. Here's an example of how to display an alert after a delay of 3 seconds:
1@objc func showAlert() {2 let alertController = UIAlertController(title: "Alert", message: "This is an alert", preferredStyle: .alert)3 present(alertController, animated: true)4}5
6let timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(showAlert), userInfo: nil, repeats: false)