3

Been looking around to find a way to detect when an app is uninstalling/reinstalling. The thing is, I do not use NSUserDefaults, I use SwiftKeychainWrapper.

I need to clear that user's keychain when app uninstalls.

didFinishLaunchingWithOptions seems to call when app loads so no use there. Is there a way to detect a reinstall? I need to call this:

return KeychainWrapper.standard.removeObject(forKey: "myKey") // only when/if app is unsinstalled/reinstalling
Community
  • 1
  • 1
Sylar
  • 11,422
  • 25
  • 93
  • 166

2 Answers2

3

Presumably you're using Keychain because you need to store sensitive information? If so then you could just store a boolean in UserDefaults and check if that exists. For example:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let freshInstall = !UserDefaults.standard.bool(forKey: "alreadyInstalled")
    if freshInstall {
        // delete your item from keychain
        UserDefaults.standard.set(true, forKey: "alreadyInstalled")
    }

    return true
}

This way you still have the security of the Keychain, but the behaviour of UserDefaults on uninstall/reinstall.

FelixSFD
  • 6,052
  • 10
  • 43
  • 117
Jacob King
  • 6,025
  • 4
  • 27
  • 45
  • Thanks. There seem to be an issue with SwiftKeychainWrapper; your method do called at the correct time so hence I make this answer correct. Thanks. – Sylar Feb 13 '17 at 16:44
  • This code doesn't provide an information that contains a reinstallation or uninstallation of an app. It just tells you that I'm a new app. – aytek Feb 13 '17 at 17:25
  • @ayteq Completely true, however unfortunately there is no way to invoke code when your app is deleted on non-jailbroken devices, this approach achieves the same goal in a roundabout way however, and the OP did specify in his question that checking upon re-install was fine for his scenario. – Jacob King Feb 14 '17 at 07:51
1

for others searching for the way to clear the Keychain in the "// delete your item" part of the answer.....

Swift 3

let _ = KeychainWrapper.standard.removeAllKeys()
Apps-n-Add-Ons
  • 2,026
  • 1
  • 17
  • 28