Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving Date in UserDefaults of the first time the App was opened

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?

like image 596
Joe Avatar asked Mar 04 '23 22:03

Joe


1 Answers

  1. There's no need for register(defaults:).
  2. Don't use 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")
}
like image 189
rmaddy Avatar answered May 09 '23 06:05

rmaddy