
- Swift Tutorial
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Data Types
- Swift - Variables
- Swift - Optionals
- Swift - Tuples
- Swift - Constants
- Swift - Literals
- Swift - Operators
- Swift - Decision Making
- Swift - Loops
- Swift - Strings
- Swift - Characters
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift - Functions
- Swift - Closures
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift - Initialization
- Swift - Deinitialization
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Type Casting
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift Useful Resources
- Swift - Compile Online
- Swift - Quick Guide
- Swift - Useful Resources
- Swift - Discussion
How can I use Timer (formerly NSTimer) in Swift?
You can use the Timer class in Swift to create a timer that can execute a method repeatedly at a specified time interval. You can implement the timer to solve different problems. You can schedule repeatable and non-repeatable timers in Swift.
Timers in Swift can be used to perform a variety of tasks, such as −
The process of carrying out a specific action or chunk of code at specified intervals of time, such as updating a display or changing a label's content, or performing any other UI action.
Sending a reminder or establishing a background activity that will launch on a specific day and time. The timer makes this process very handy in iOS apps.
Calling a method or code block frequently enough to create an animation or game loop while updating the status of the objects on the screen.
By implementing a timer to decrement a counter and updating a label or displaying an alert when the countdown approaches zero, a countdown timer can be implemented.
Establishing a timer before beginning a task, stopping it after it is complete, and then calculating the time interval to determine how long it took.
Controlling how a code runs by, for example, pausing or terminating an activity when a timer goes off or starting an event when a certain amount of time has passed.
Carrying out background operations, such as retrieving information from a server or changing an object's status.
These are just a few examples of what can be done with timers in Swift, and the possibilities are virtually endless.
Repeating Vs Non-repeating Timers
Repeating timers and non-repeating timers are two types of timers in Swift, with different applications.
A repeating timer is a timer that repeatedly calls a method or block of code at a specified time interval. A repeating timer can be created using the Timer.scheduledTimer(withTimeInterval:repeats:block:) method, by setting the repeats parameter to true.
Example
let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in // code to be executed every 1 second print("A repeating timer has executed.") }
Non-repeating timers commonly referred to as one-shot timers, call a method or block of code just once before invalidating itself. By setting the repeats parameter to false, a non-repeating timer can be built using the same technique as a repeating timer.
Example
let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in // code to be executed after 1 second print("A repeating timer has executed.") }
Refreshing a view or altering the content of a label are two examples of repetitive chores that can benefit from repeating timers. Non-repeating timers are helpful for jobs that need to be done just once, like setting a reminder or starting an event after a certain amount of time has passed.
Note − You should invalidate preparing time when you no longer need it. This is because it will continue to execute code and consume resources.
How to set a repeat timer?
You can schedule a repeating task in Swift using the Timer class.
Example
Here is an example of how to schedule a task that runs every 5 seconds and prints "timer has executed" on the console −
import UIKit class TestController: UIViewController { private var timer: Timer? override func viewDidLoad() { super.viewDidLoad() // scheduling a timer in repeat mode after every 5 seconds. self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(handleTimerExecution), userInfo: nil, repeats: true) } @objc private func handleTimerExecution() { print("timer has executed") } }
The handleTimerExecution() function, which is accessible through the @objc attribute, is a handy feature of Objective-C. The timer class is a component of the Objective-C runtime, thus the @objc tag is also required.
You can use iOS's target-action capability to call a specific function on a specific object. We define "action" as the method that is called by the action method, which has the object it is supposed to be called on as its target.
How we can send a message with a timer?
You can send userInfo with a timer in Swift by using the userInfo property of the Timer class. The userInfo property is an optional property that can hold any type of data that you want to pass to the block of code that the timer executes.
Example
Here is an example of how to pass a message as user Info to a timer −
import UIKit class TestController: UIViewController { private var timer: Timer? override func viewDidLoad() { super.viewDidLoad() let userInfo: [String: Any] = ["fullName": "Albert Martin", "age": 23, "country": "USA"] // scheduling a timer in repeat mode after each 5 seconds. self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(handleTimerExecution), userInfo: userInfo, repeats: true) } @objc private func handleTimerExecution(_ timer: Timer) { if let userInfo = timer.userInfo as? [String: Any] { print("User info: \(userInfo)") // invalidate the timer after receiving the user info. self.timer?.invalidate() } // here is a fallback to end the timer if userInfo is not found } }
Output
User info: ["fullName": "Albert Martin", "age": 23, "country": "USA"]
How can we stop a repeating timer?
You can stop a repeating timer in Swift by using the invalidate() method of the Timer class.
The invalidate() method stops the timer and releases its resources, so it will no longer execute the block of code associated with it.
Example
Here is an example of how to stop a repeating timer −
import UIKit class TestController: UIViewController { private var timer: Timer? private var timerCurrentCount = 0 override func viewDidLoad() { super.viewDidLoad() // scheduling a timer in repeat mode after every 5 seconds. self.timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(handleTimerExecution), userInfo: nil, repeats: true) } @objc private func handleTimerExecution() { // check for max execution count of timer. if self.timerCurrentCount == 5 { self.timer?.invalidate() // invalidate the timer print("Timer invalidated") } else { print("Timer executed") self.timerCurrentCount += 1 } } }
Output
Timer executed Timer executed Timer executed Timer executed Timer executed Timer invalidated
It's crucial to understand that the memory occupied by the timer is not instantly released by the invalidate() method. It will be made available when the system deems it appropriate.
Additionally, it's good practice to shut off the timer when you're done using it to avoid it using up resources and degrading the functionality of your application.
Conclusion
As a result, Swift timers are a practical tool for planning and carrying out tasks at certain intervals or dates. Creating recurring and non-repeating timers is made simple by the Timer class, and the userInfo property enables you to supply any kind of data to the block of code that contains the timer. Use the Timer class' invalidate() function to discontinue a timer.
You can terminate a timer by calling the Timer class' invalidate() function. In order to keep a timer from using resources and degrading the functionality of your app, it's crucial to remember to stop it when you're done with it.
- Related Articles
- How can I extend typed arrays in Swift?
- How can we implement a timer thread in Java?
- How can I encode a string to Base64 in Swift?
- How can I use Web Workers in HTML5?
- How can I use goto statement in JavaScript?
- How can I use Multiple-tuple in Python?
- How can I use marquee text in Kotlin?
- How can I use wstring(s) in Linux APIs
- How can I make a button have a rounded border in Swift?
- How to use UICollectionView in Swift?
- Can I change the size of UIActivityIndicator in Swift?
- How can I use the HTML5 canvas element in IE?
- How can I use Marquee text in an android app?
- How can I use multiple submit buttons in an HTML form?
- How can I use MySQL IN() function to compare row constructors?
