Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a piece of code only once in swift?

Tags:

ios

swift

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.

like image 896
pogbamessi Avatar asked Nov 18 '15 19:11

pogbamessi


1 Answers

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.

like image 112
Mr Beardsley Avatar answered Oct 12 '22 23:10

Mr Beardsley