SwiftUI: How to cancel timer in SwiftUI view?

Inside your conditional statement, use the following code:

self.timer.upstream.connect().cancel()

Full cycle goes like this:

struct MySwiftUIView : View {
...

@State var timer = Timer.publish (every: 1, on: .current, in: .common).autoconnect()
@State var timeRemaining = -1

var body: some View {
    ZStack {
       // Underlying shapes etc as needed

       Text("\(timeRemaining)").
           .opacity(timeRemaining > 0 ? 1 : 0)
           .onReceive(timer) { _ in
                if self.timeRemaining < 0 {
                    // We don't need it when we start off
                    self.timer.upstream.connect().cancel()
                    return
                }
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                } else {
                    self.timer.upstream.connect().cancel()
                    // Do the action on end of timer. Text would have been hidden by now
                }
          }
          .onTapGesture {  // Or any other event handler that should start countdown
                self.timeRemaining = Int(delayValue)
                self.timer = Timer.publish (every: 1, on: .current, in: 
                                                   .common).autoconnect()
          }
    }

Voila! A reusable timer, use it as many times as you'd like!

Tags:

Timer

Swiftui