How to detect an iOS App installed or upgraded? [duplicate]

那年仲夏 提交于 2019-11-30 03:39:25

You can differentiate between the first start after installing the App, the first start after an update and other starts quite easily via saving the latest known version to standardUserDefaults. But as far as I know it is not possible do detect a re-install of the App as all App-related data are also removed when the App is deleted from the device.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSString* currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    NSString* versionOfLastRun = [[NSUserDefaults standardUserDefaults] objectForKey:@"VersionOfLastRun"];

    if (versionOfLastRun == nil) {
        // First start after installing the app
    } else if (![versionOfLastRun isEqual:currentVersion]) {
        // App was updated since last run
    } else {
        // nothing changed 
    }

    [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:@"VersionOfLastRun"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

Checkout Swift 3.0 version of code.
Note: Use CFBundleShortVersionString, for checking actual App version checking.

func checkAppUpgrade() {
    let currentVersion = Bundle.main.object(forInfoDictionaryKey:     "CFBundleShortVersionString") as? String
    let versionOfLastRun = UserDefaults.standard.object(forKey: "VersionOfLastRun") as? String

    if versionOfLastRun == nil {
        // First start after installing the app

    } else if versionOfLastRun != currentVersion {
        // App was updated since last run

    } else {
        // nothing changed

    }

    UserDefaults.standard.set(currentVersion, forKey: "VersionOfLastRun")
    UserDefaults.standard.synchronize()
}

For Swift 3

 let currentVersion : String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String

let versionOfLastRun: String? = UserDefaults.standard.object(forKey: "VersionOfLastRun") as? String

if versionOfLastRun == nil {
     // First start after installing the app
} else if  !(versionOfLastRun?.isEqual(currentVersion))! {
      // App is updated
}

UserDefaults.standard.set(currentVersion, forKey: "VersionOfLastRun")
UserDefaults.standard.synchronize()

Just for note:

To obtain localized value of any key you should use CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), "CFBundleShortVersionString" as CFString)

Please store a version in NSUserDefaults (per @Nero's answer) for checking (possible) fresh installs and subsequent updates.

For checking reinstalls (in the case where stored version == nil), exploit iOS 11's introduction of DeviceCheck API which exposes two bits of device specific data which can be set and retrieved by the app, but maintained by Apple and persisted across an uninstall/reinstalls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!