Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a MenuBarExtra that updates on timer

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
            }
        }
    }
}
like image 650
exclipy Avatar asked Sep 12 '25 23:09

exclipy


1 Answers

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)")
        }
    }
}
like image 100
exclipy Avatar answered Sep 15 '25 15:09

exclipy