Search code examples
iosobjective-ckeychain

Delete keychain items when an app is uninstalled


I am using idandersen's scifihifi-iphone code for keychain and save password using

[SFHFKeychainUtils storeUsername:@"User" andPassword:@"123"
              forServiceName:@"TestService" updateExisting:YES error:&error];

When I delete the application from the device, the password remains in the keychain.

I want to remove the password from the keychain when the user deletes the application from the device. How can I do this?


Solution

  • You can take advantage of the fact that NSUserDefaults are cleared by uninstallation of an app. For example:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        //Clear keychain on first run in case of reinstallation
        if (![[NSUserDefaults standardUserDefaults] objectForKey:@"FirstRun"]) {
            // Delete values from keychain here
            [[NSUserDefaults standardUserDefaults] setValue:@"1strun" forKey:@"FirstRun"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    
        //...Other stuff that usually happens in didFinishLaunching
    }
    

    This checks for and sets a "FirstRun" key/value in NSUserDefaults on the first run of your app if it's not already set. There's a comment where you should put code to delete values from the keychain. Synchronize can be called to make sure the "FirstRun" key/value is immediately persisted in case the user kills the app manually before the system persists it.