I am trying to set the Date()
the very first time an App is opened. This will be set in UserDefaults
.
I used register()
to save the date in UserDefault. The problem is.. this value seems to be saving on every launch, which defeats the purpose of UserDefaults.register.
Here is my code:
let initialOpen: NSDictionary = ["FirstOpen" : Date()]
UserDefaults.standard.register(defaults: initialOpen as! [String : AnyObject])
let firstOpenDate = UserDefaults.standard.value(forKey: "FirstOpen")
print("First Opened: \(firstOpenDate)")
I am calling this within didFinishLaunchingWithOptions
.
How can I record the time that the App is launched for the first time in UserDefaults?
register(defaults:)
.value(forKey:)
to read data from UserDefaults
.All you need to do is first check if the date has been set, if not, set it.
if let firstOpen = UserDefaults.standard.object(forKey: "FirstOpen") as? Date {
print("The app was first opened on \(firstOpen)")
} else {
// This is the first launch
UserDefaults.standard.set(Date(), forKey: "FirstOpen")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With