Updating SwiftUI view for every x seconds

Sai Durga Mahesh
2 min readOct 11, 2021
Photo by Markus Winkler on Unsplash

With the evolution of SwiftUI, even smaller things in iOS Development became worth re-visiting.

In this article we will update a SwiftUI View for every 1 second using few possible ways.

With Combine — ViewModel:

Just created a View Model with timer and small refresh fresh function which increments index and update date. And now we can use the View Model inside SwiftUI View.

With Just StateObject instance the view refreshes every second. The @State instance is just to show that we can still maintain state of view.

With TimelineView

Starting with iOS15, we can use new TimelineView to update view periodically. We get timeline instance having date at which update triggered and rate at which update happening. This helps in refreshing the view for every second. This view shows output as follows:

Apart from achieving the 1 second refresh, the “lower bound must be less than upper bound” condition might be reason behind delay.

With In Place Timer

Here again we just used Combine to publish update for every second.

That’s it !!!

Thanks for Reading…

--

--

Sai Durga Mahesh

Using Data Science to provide better solutions to real word problems