0

I have a requirement of detecting the first launch of app after the user upgrades the app to a newer version. I need to perform certain task only on first launch of app after the user upgrades the app to a new version. Many links available online but none answer clearly to my query. How to achieve this in Swift 2 , iOS 9.

Most of the answers available says to maintain a key in NSUserDefaults and set its value to false and after first launch make it true. But the problem is after I upgrade my app the variable still will be true and thus my scenario fails on app upgrade. Any help would be much appreciated. Thanks!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Tejas
  • 1,050
  • 12
  • 23
  • 1
    Just do the same, but instead of saving a boolean, save the build/app version. It's in your Info.plist: http://stackoverflow.com/questions/1492351/how-to-display-the-current-project-version-of-my-app-to-the-user Read it, if it's the same, no update, if not, new version, and write it. – Larme Oct 13 '16 at 12:30
  • @Larme Thanks! But, Can you describe in little more detail please? If I am not wrong you mean to say that, I should compare the version, and if there is change in version number then this task runs, else not. Is that correct? – Tejas Oct 13 '16 at 12:34
  • 1
    In pseudo code, this should to the trick: `savedVersion = readStringVersionFromUserDefault(); currentVersion = readStringVersionFromBundlePlist(); if (savedVersion.isNil or currentVersion != savedVersion){firstTimeUserLaunchedThisVersion(); saveStringVersionFromBundlePlistIntoUserDefaults();}else{UserHasAlreadyLaunchedThisVersion}` – Larme Oct 13 '16 at 12:53
  • thank you @Larme I know its very late reply :P – Tejas Nov 28 '18 at 11:50

2 Answers2

3

Try this:

    let existingVersion = NSUserDefaults.standardUserDefaults().objectForKey("CurrentVersionNumber") as? String
    let appVersionNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String

    if existingVersion !=  appVersionNumber {
        NSUserDefaults.standardUserDefaults().setObject(appVersionNumber, forKey: "CurrentVersionNumber")
        NSUserDefaults.standardUserDefaults().synchronize()
       //You can handle your code here
    }
Yogesh Mv
  • 1,041
  • 1
  • 6
  • 12
3

updating Yogesh's perfect, yet simple solution to swift 4

    let existingVersion = UserDefaults.standard.object(forKey: "CurrentVersionNumber") as? String
    let appVersionNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String

    if existingVersion != appVersionNumber {
        print("existingVersion = \(String(describing: existingVersion))")
        UserDefaults.standard.set(appVersionNumber, forKey: "CurrentVersionNumber")

 // run code here.

    }
David Sanford
  • 735
  • 12
  • 26