I want to run a piece of code which sets a variable to true when the app is launched for the first time and then sets it to false so that it doesn't run again. In short, it should run only once in its lifetime. I have tried almost everything including dispatch_once_t
but didn't work for me. I put my code in viewDidLoad
, viewDidAppear
etc but didn't work.
What you need is persistence between app launches. Fortunately, this exists and is provided with NSUserDefaults.
I would do something like the following in your app delegate didFinishLaunching method:
let hasLaunchedKey = "HasLaunched"
let defaults = UserDefaults.standard
let hasLaunched = defaults.bool(forKey: hasLaunchedKey)
if !hasLaunched {
defaults.set(true, forKey: hasLaunchedKey)
}
// Use hasLaunched
The first time you run the app, the key will not be in the defaults database and will return false. Since it is false, we save the value of true in the defaults database, and each subsequent run you will get a value of true.
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