macosswiftui

Update variables in ContentView at midnight


I have the following variables in my ContentView file

let DOY = getDayOfYear()
let DRNoW = daysinyear()
let WN = weekNumber()
let DN = dayNumber()

And using the func of:

func getDayOfYear() -> Int {
    let date = Date() // now
    let cal = Calendar.current
    let day1 = cal.ordinality(of: .day, in: .year, for: date)!

    return day1
}

I want the variables to update at midnight in the ContentView.

How do I make it happen?


Solution

  • You could subcribe to NSCalendarDayChanged

    struct ContentView: View {
        var body: some View {
            ...
            .onReceive(NotificationCenter.default
                .publisher(for: NSNotification.Name.NSCalendarDayChanged)) { (output) in
                // Update variables at midnight here
            }
        }
    }