I'm trying to write my first Swift app for MacOS. For now, I just want a menubar app that counts up every second but it's not working. Can anyone help, please?
import SwiftUI
class ThirdTimerStore: ObservableObject {
@Published var workedSeconds: Int = 0
}
@main
struct Third_TimerApp: App {
@StateObject var store = ThirdTimerStore()
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some Scene {
MenuBarExtra("\(store.workedSeconds)") {
Text("Time: \(store.workedSeconds)").onReceive(timer) { _ in
store.workedSeconds += 1
}
}
}
}
Managed to get it thanks to this post with:
import SwiftUI
class ThirdTimerStore: ObservableObject {
@Published var workedSeconds: Int = 0
var timer: Timer?
init() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in
self.workedSeconds += 1
})
}
deinit {
timer?.invalidate()
}
}
@main
struct Third_TimerApp: App {
@StateObject var store = ThirdTimerStore()
var body: some Scene {
MenuBarExtra("\(store.workedSeconds)") {
Text("Time: \(store.workedSeconds)")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With