Implementing Polling in SwiftUI

Abdul Karim Khan
3 min readAug 29, 2023

--

Polling is a common technique used in software development to continuously check for updates or changes in a specific interval. In SwiftUI, polling can be implemented to perform various tasks, such as fetching data from a server, updating UI elements, or monitoring changes in a system. In this article, we will delve into the concept of polling in Swift, explore its use cases, and provide practical examples of its implementation.

Understanding Polling

Polling involves repeatedly checking a condition or performing an action at regular intervals. It’s a process of repeatedly asking a question: “Has anything changed?” If the answer is “yes,” an appropriate action is taken. Polling is commonly used when real-time updates or notifications are not feasible, and regular checking is the best available solution.

Use Cases for Polling

  1. Data Synchronisation: Polling can be used to keep local data synchronised with a remote server. For example, a weather app might poll a weather API at regular intervals to ensure that users receive up-to-date information.
  2. User Interface Updates: Polling can update UI elements such as notifications or live feeds. Social media platforms often use polling to display real-time updates on user feeds.
  3. Resource Availability: In cases where resources like network availability or system processes are fluctuating, polling can be used to detect when resources become available.
  4. Monitoring Changes: Polling can monitor changes in user settings or preferences and adapt the application accordingly.

Implementing Polling in SwiftUI

Let’s take a look at a simple example of how to implement polling in SwiftUI:

Let’s create a generic Polling Manager class with start and stop polling actions,

class PollingManager<T>: ObservableObject {
let pollingInterval: TimeInterval
private var pollingTimer: Timer?
private var pollingAction: (() -> Void)?

init(pollingInterval: TimeInterval) {
self.pollingInterval = pollingInterval
}

func startPolling(pollingAction: @escaping () -> Void) {
self.pollingAction = pollingAction
self.pollingTimer = Timer.scheduledTimer(
withTimeInterval: pollingInterval,
repeats: true
) { _ in
self.pollingAction?()
}
}

func stopPolling() {
pollingTimer?.invalidate()
pollingTimer = nil
pollingAction = nil
}
}

Next, let’s use this class in our main view.

struct ContentView: View {
@ObservedObject private var pollingManager = PollingManager<String>(pollingInterval: 2.0)
@State var numberOfTimePolled = 0

var body: some View {
VStack {
Text("Polling Example")
Text("\(numberOfTimePolled)")
}
.onAppear {
pollingManager.startPolling {
self.pollingAction()
}
}
.onDisappear {
pollingManager.stopPolling()
}
}

func pollingAction() {
// Perform your polling logic here
print("Polling...")
numberOfTimePolled += 1
}
}

We have successfully implemented polling using generic polling manager class. This class can be utilise at multiple places within app.

Polling Best Practices

  1. Optimise Interval: Choose an appropriate polling interval based on the nature of your application and the urgency of updates. Longer intervals reduce server load and battery consumption.
  2. Graceful Handling: Handle potential errors or unavailability of resources gracefully to prevent unnecessary polling and wasted resources.
  3. Use Efficient APIs: Use efficient APIs to minimize the amount of data exchanged during each polling iteration.
  4. Consider Alternatives: Depending on your use case, alternatives like push notifications or reactive programming libraries might provide more efficient solutions.

Conclusion

Swift polling provides a convenient approach to continually monitor changes, get data, and update UI components. Developers may construct applications that give timely and relevant information to consumers by knowing the fundamentals of polling and intelligently applying it. Remember to optimise intervals, manage mistakes, and investigate alternate ways for more efficient solutions when you include polling into your Swift programmes.

--

--