Skip to content

Instantly share code, notes, and snippets.

@mariosaputra
Created May 19, 2024 22:51
Show Gist options
  • Save mariosaputra/9ad4586ad89ed2f3eccc1f2089bcd8cd to your computer and use it in GitHub Desktop.
Save mariosaputra/9ad4586ad89ed2f3eccc1f2089bcd8cd to your computer and use it in GitHub Desktop.
Update UI when the date changes
import SwiftUI
struct ContentView: View {
@Environment(\.scenePhase) var scenePhase
@State private var startOfToday = Calendar.current.startOfDay(for: Date.now)
@State private var timer: Timer?
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .none
return formatter
}
var body: some View {
Text(dateFormatter.string(from: startOfToday))
.id(startOfToday)
.font(.title)
.onChange(of: scenePhase) { _, newPhase in
if newPhase == .active {
checkIfDateHasChanged()
} else if newPhase == .background {
// Invalidate the timer when the app goes to the background
timer?.invalidate()
timer = nil
}
}
.onAppear {
startTimer()
}
}
func checkIfDateHasChanged() {
if startOfToday != Calendar.current.startOfDay(for: Date.now) {
print("INFO: - Date has changed, updating UI.")
startOfToday = Calendar.current.startOfDay(for: Date.now)
}
}
func startTimer() {
// Calculate the time interval until the next midnight
let calendar = Calendar.current
let now = Date()
let nextMidnight = calendar.nextDate(after: now, matching: DateComponents(hour: 0), matchingPolicy: .strict)!
let timeInterval = nextMidnight.timeIntervalSince(now)
// Schedule a timer to fire at the next midnight
timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false) { _ in
checkIfDateHasChanged()
startTimer() // Restart the timer for the next midnight
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment