Count number of times app has been launched using Swift?

前端 未结 2 407
挽巷
挽巷 2020-12-31 04:59

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

2条回答
  •  旧巷少年郎
    2020-12-31 05:15

    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.

提交回复
热议问题