so I'll keep it simple: I have a timer that runs on appear of this view as follows:
struct FocusView: View {
@State var isTimerRunning = false
@State private var startTime = Date()
@State private var timerString = "0.00"
@State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
NavigationView {
VStack {
Text(self.timerString)
.font(Font.system(.largeTitle, design: .monospaced))
.onReceive(timer) { _ in
if self.isTimerRunning {
timerString = String(format: "%.2f",(Date().timeIntervalSince( self.startTime)))
}
}
.onTapGesture {
if isTimerRunning {
self.stopTimer()
soundManager.stopSound()
//statee.hideTabView = false
} else {
timerString = "00.00.00"
startTime = Date()
self.startTimer()
soundManager.playSoundFocus()
selected = 3
}
}
.onAppear() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
if isTimerRunning {
}
else {
// no need for UI updates at startup
timerString = "00.00.00"
startTime = Date()
// start UI updates
self.startTimer()
}
}
}
func stopTimer() {
self.timer.upstream.connect().cancel()
isTimerRunning = false
// isMusicPlaying = false
}
func startTimer() {
self.timer = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()
isTimerRunning = true
// isMusicPlaying = true
}
Now when I go to some other view via tab view (let's call is view B) the timer still keeps running. BUT, the moment I go inside a navigation link inside view B the timer stops. Does anyone know how can I keep running the timer? I'm not sure if it's a navigation link issue or a tab view issue. Would appreciate any input. Thanks!