How to declare variables for `Timer.publish()`

Viewed 1253

I'm currently developing an application using SwiftUI.

I'm trying to make a timer app and I want to control Timer.publish() method, so I made methods to start and stop the timer.

But I don't know how to declare variables for Timer.publish() and then the codes don't work...

How could I declare variables for Timer.publish()?


ContentView.swift (*This code doesn't build)

import SwiftUI

struct ContentView: View {
    
    @State var timer:Timer! //I don't know how to declare here...
    @State var counter = 0
    
    var body: some View {
        VStack{
            HStack{
                Text("RUN")
                    .onTapGesture {
                        startTimer()
                        
                    }
                Text("STOP")
                    .onTapGesture {
                        stopTimer()
                    }
            }
            
            Text(String(counter))
                .padding()
        }
        
        .onReceive(timer) { _ in
            print("onRecieve")
            counter += 1
            
        }
    }
    
    func stopTimer() {
        self.timer.upstream.connect().cancel()
    }
    
    func startTimer() {
        self.timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    }
}

TimerControlApp.swift

import SwiftUI

@main
struct TimerControlApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Xcode: Version 12.0.1

iOS: 14.0

Life Cycle: SwiftUI App

1 Answers

In order to control the start, your timer should be of type Timer.TimerPublisher. That way you can start the timer using .connect() manually.

@State var timer: Timer.TimerPublisher = Timer.publish(every: 1, on: .main, in: .common)
func startTimer() {
    timer = Timer.publish(every: 1, on: .main, in: .common)
    _ = timer.connect()
}
func stopTimer() {
    timer.connect().cancel()
}
Related