Reputation: 21
How can I reset the variable after one day? I have used this code but this code removes the values from the overall app, not from the particular variable.
How can we reset particular variable after one day with UserDefaults
and without UserDefaults
?
extension UserDefaults {
static let defaults = UserDefaults.standard
static var lastAccessDate: Date? {
get {
return defaults.object(forKey: "lastAccessDate") as? Date
}
set {
guard let newValue = newValue else { return }
guard let lastAccessDate = lastAccessDate else {
defaults.set(newValue, forKey: "lastAccessDate")
return
}
if !Calendar.current.isDateInToday(lastAccessDate) {
print("remove Persistent Domain")
UserDefaults.reset()
}
defaults.set(newValue, forKey: "lastAccessDate")
}
}
static func reset() {
defaults.removePersistentDomain(forName: Bundle.main.bundleIdentifier ?? "")
}
}
Upvotes: 1
Views: 864
Reputation: 4918
Your reset function removes all UserDefaults associated with you app.
To remove a particular key use this:
UserDefaults.standard.removeObject(forKey: "lastAccessDate")
Upvotes: 1