I use "UserDefaults" to store the date time of the user to reload the page. However, I found that it does not refresh even if the time passed
final class ModelData: ObservableObject {
@Published var lastLaunchDate: Date = UserDefaults.standard.value(forKey: "lastLaunch") as? Date ?? Date()
func getTimeStamp() -> Date {
let now_components = Calendar.current.dateComponents([.month, .day, .hour, .minute], from: Date())
let lastLaunch_components = Calendar.current.dateComponents([.month, .day, .hour, .minute], from: lastLaunchDate)
print(now_components.minute, lastLaunch_components.minute)
if now_components.minute != lastLaunch_components.minute {
lastLaunchDate = Date()
UserDefaults.standard.setValue(lastLaunchDate, forKey: "lastLaunch")
}
print(now_components.minute, lastLaunch_components.minute)
}
return lastLaunchDate
}
}
Since I am testing, I use 'minute' to ease my test. I expect that when there is change of minute, the above piece of code will update my userDefaults.
struct HomeView: View {
@EnvironmentObject var modelData: ModelData
var body: some View {
Text("\(modelData.getTimeStamp())")
}
}
I found that I browse into another page, go back to HomeView. The timestamp did not get update at all. I printed the lastLaunchDate, it also did not update as well.