David Sanford
David Sanford

Reputation: 745

Knowing if user updates app or if a new purchase (swift 3)

Is is possible to know if the user is installing a new purchase or if they are downloading an update in Swift?

I have seen this question via Android and Obj C, but not in Swift.

I am using a SQLite database, if that helps.

Upvotes: 2

Views: 1379

Answers (1)

dirtydanee
dirtydanee

Reputation: 6151

Keep track of the application version in UserDefaults. I am not sure, what have you find for Objective C, but i am sure, it has kinda the same idea.

Lets say you keep track of the versions of your app under the key appVersion in UserDefaults. Than you just read it, compare it with your current application version, and check the comparison results.
You can do this in AppDelegate's

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

so every time your app starts, the current app version will be updated in UserDefaults.

Example for Swift 3

let defaults = UserDefaults.standard    
guard let currentAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, let previousVersion = defaults.string(forKey: "appVersion") else {
      // Key does not exist in UserDefaults, must be a fresh install
      print("fresh install")
      //  Writing version to UserDefaults for the first time
      defaults.set(currentAppVersion, forKey: "appVersion")
      return
}

let comparisonResult = currentAppVersion.compare(previousVersion, options: .numeric, range: nil, locale: nil)
switch comparisonResult {
    case .orderedSame:
        print("same version is running like before")
    case .orderedAscending:
        print("earlier version is running like before")
    case .orderedDescending:
        print("older version is running like before")
}

// Updating new version to UserDefaults
defaults.set(currentAppVersion, forKey: "appVersion")

Upvotes: 3

Related Questions