NEW: Nominations are now open for the 2019 Swift Community Awards! >>

How to use a timer with SwiftUI

Paul Hudson    @twostraws   

Fully updated for Xcode 11.1

If you want to run some code regularly, perhaps to make a countdown timer or similar, you should use Timer and the onReceive() modifier.

For example, this code creates a timer publisher that fires every second, updating a label with the current time:

struct ContentView: View {
    @State var currentDate = Date()
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        Text("\(currentDate)")
            .onReceive(timer) { input in
                self.currentDate = input
            }
    }
}

It’s important to use .main for the runloop option, because our timer will update the user interface. As for the .common mode, that allows the timer to run alongside other common events – for example, if the text was in a scroll view that was moving.

As you can see, the onReceive() closure gets passed in some input containing the current date. In the code above we assign that straight to currentDate, but you could use it to calculate how much time has passed since a previous date.

If you specifically wanted to create a countdown timer or stopwatch, you should create some state to track how much time remains, then subtract from that when the timer fires.

For example, we could create a countdown timer that shows time remaining in a label, like this:

struct ContentView: View {
    @State var timeRemaining = 10
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        Text("\(timeRemaining)")
            .onReceive(timer) { _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                }
            }
    }
}

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

Similar solutions…

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 1.0/5