UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 {
                            countdownSound.play()
                        } 
                        } else if self.timeRemaining == 0 {
                        playFinishSound()

                    } 
        }

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.