Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of times app has been launched using Swift?

Tags:

ios

swift

I would like to count the number of times my iOS application has been launched using Swift.

I would then like to take the number and display it using NSLog each time.

like image 772
Daniel Bramhall Avatar asked Aug 12 '15 13:08

Daniel Bramhall


2 Answers

Add this in AppDelegate in applicationDidFinishLaunching method.

Swift 3 and Swift 4:

// get current number of times app has been launched
let currentCount = UserDefaults.standard.integer(forKey: "launchCount")

// increment received number by one
UserDefaults.standard.set(currentCount+1, forKey:"launchCount")

Swift 2:

// get current number of times app has been launched
let currentCount = NSUserDefaults.standardUserDefaults().integerForKey("launchCount")

// increment received number by one
NSUserDefaults.standardUserDefaults().setInteger(currentCount+1, forKey:"launchCount")

According to documentation there's no more need to call:

UserDefaults.standard.synchronize()

Waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used.

like image 179
Juri Noga Avatar answered Nov 07 '22 05:11

Juri Noga


You can store a int to NSUserDefaults.

Every time when you load the app, you can increase the number and save it again.

Add this logic in ApplicationDidFinishLaunching method.

Hope this helps.

like image 2
Bharat Nakum Avatar answered Nov 07 '22 05:11

Bharat Nakum