WWDC21 SALE: Save 50% on all my Swift books and bundles! >>

SwiftUI timer runloop

Forums > SwiftUI

I'm making a game with rounds of a set time and the user can start a timer and swipe through cards. However, whenever I interact with the UI the timer pauses. I tried changing the runloop mode but Swift is giving me compiler errors. I'm doing this all in SwiftUI and Combine with the example code below.

I would appreciate any help or advice for how to prevent the timer from stopping

@State private var timeRemaining = Defaults.roundLength
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    init() {
        RunLoop.current.add(timer, forMode: .common) //Swift is giving me error "No exact matches in call to instance method 'add'"

    var body: some View {
      Text("\(timeRemaining/60):\(String(format: "%02d", (self.timeRemaining % 60)))")
                .onReceive(timer) { time in
                    if self.timeRemaining > 0 {
                        self.timeRemaining -= 1
                        if self.timeRemaining <= 10 {
                        } else if self.timeRemaining == 0 {



Save money with our WWDC sale!

SAVE 50% To celebrate WWDC21, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.