0

I'm trying to debug a strange behavior while saving to the users keychain on iOS. I'm using the below code to check for the user being on the keychain:

keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:KeyName accessGroup:nil];
if(keychainItem != NULL && [keychainItem objectForKey:(id)kSecValueData] != NULL && [[keychainItem objectForKey:(id)kSecValueData] length] > 0  &&
        [keychainItem objectForKey:(id)kSecAttrAccount] != NULL && [[keychainItem objectForKey:(id)kSecAttrAccount] length] > 0) {

    txtPassword.text = [keychainItem objectForKey:(id)kSecValueData];
    txtLogin.text = [keychainItem objectForKey:(id)kSecAttrAccount];

    // Call webservice to login
    [self btnPressedLogin:nil];
}

I'm using the following for saving to the keychain:

[keychainItem setObject:KeyName forKey: (id)kSecAttrService];
[keychainItem setObject:txtLogin.text forKey:(id)kSecAttrAccount];
[keychainItem setObject:txtPassword.text forKey:(id)kSecValueData];

When the user logs out, I simply do:

[keychainItem resetKeychainItem];

I'm noticing it works in all scenarios EXCEPT:

  1. I log in (manually entering username/password)
  2. Log out
  3. I log in (manually entering username/password)
  4. Restart simulator
  5. It DOESN'T auto-login as it should

Is there something wrong with my code snippets above? I'm able to reproduce this on the simulator each time, and i'm not aware, as I was following tutorials online. Including the following page:

iOS: How to store username/password within an app?

[EDIT]

I was stepping through breakpoints, and I confirmed that after step 3 (relogging in), it is in fact saving to the keychain. I was able to output what it saved.

However, right after that when I restart the simulator...it shows that it can't find username and password! Which makes no sense...

Community
  • 1
  • 1
KVISH
  • 12,923
  • 17
  • 86
  • 162

1 Answers1

0

I found the issue. It was a memory issue. When the screen was moving, keychainItem was a property that was being deallocated. I had to reinitialize it since I was creating in the viewDidLoad function, which wasn't getting called after logging out. Case closed.

KVISH
  • 12,923
  • 17
  • 86
  • 162