20

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.

3
  • don't use NSLog in Swift, rather use print() and println()
    – nburk
    Aug 12, 2015 at 13:44
  • 1
    Out of curiosity, how come? Aug 12, 2015 at 13:47
  • nburk's comment was reasonable when written, but I Am From The Future and here we have oslog() (Unified Logging) as the current best practice for logging. Unified Logging OSLog Jul 27, 2020 at 4:42

2 Answers 2

37

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.

6
  • 1
    I get an error using the .setInteger as I don't think it accepts currentCount+=1 as an argument. Aug 12, 2015 at 13:48
  • change currentCount+=1 to currentCount+1 and it should work! :)
    – nburk
    Aug 12, 2015 at 13:51
  • Thanks a lot, I changed it to currentCount++ but had no luck. currentCount+1 does the trick. Aug 12, 2015 at 13:53
  • If you are looking for how many times user has launched the app this is NOT what you want to do. the applicationDidFinishLaunching will be called by the system too without user interaction. see developer.apple.com/library/content/documentation/iPhone/… Nov 1, 2017 at 18:19
  • Not sure if it matters to you but someone with an unlocked phone could be able to change this number if you store it in user defaults. I would use core data.
    – Jevon718
    Dec 10, 2017 at 5:29
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.