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

Viewed 181523

I have a login-screen in my iOS app. The username and password will be saved in the NSUserDefaults and be loaded into the login-screen again when you enter the app again (of course, NSUserDefaults are permanent).

Now, the user have the possibility to disable the username/password saving feature.

So the NSUserDefaults will be cleared then.

But In my app I need this username/password for database queries for the user. So: Where to store the data except NSUserDefaults? (This place can / should be deleted when the user quit the app or logout).

15 Answers

try this one:

 KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];
[keychainItem setObject:@"password you are saving" forKey:kSecValueData]; 
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];

may it will help.

If your app has an associated domain it's better to use Managing Shared Credentials. It will provide the best experience for the user and it's managed by the system itself.

Step 1:

Set up your Associated Domains with webcredentials key

Step 2

Mark your text fields

userIdTextField.textContentType = .username
passwordTextField.textContentType = .password

Step 3

Use the following code to save the details whenever the user successfully login. iOS will show a confirmation action sheet for the user to save the password. And next time the user tries to login keyboard will suggest the user credentials for your app.

SecAddSharedWebCredential("www.example.com" as CFString, "user_id" as CFString, "password" as CFString) { error in
    if error != nil {
      // Handle error
      return
    }

    // The credentials have been successfully saved.
}

Now you're ready to go. Read more...?!

Related