I\'d like to use an auto-login function. So when the user opens the app, he gets delegated to a \"login screen\". When he logged in successfully he should be directed to his acc
I used a combination of NSUserDefaults and SSKeychain. I used NSUserDefaults to store the username nad SSKeychain to store the password.
This is the code I used to save the credentials
NSString *user = self.username.text;
NSString *password = self.pass.text;
[SSKeychain setPassword:password forService:@"achat" account:user];
NSUserDefaults *dUser = [NSUserDefaults standardUserDefaults];
[dUser setObject:user forKey:@"user"];
[dUser synchronize];
This is the code I used to retrieve the credentials
NSUserDefaults *eUser = [NSUserDefaults standardUserDefaults];
NSString *savedUser = [eUser objectForKey:@"user"];
if (!savedUser) {
UIAlertView *uhoh = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Please enter your username and password." delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
[uhoh show];
}
else {
NSString *savedPass = [SSKeychain passwordForService:@"achat" account:savedUser];
self.username.text = savedUser;
self.pass.text = savedPass;
}
While saving Username and Password, it is highly advised to save in Keychain rather than the NSUserDefaults. Refer this post for a better understanding.
Simply you add login credentials to keychain when user logs in and only remove it once user clicks the logout button. If user quits the app without logout then the credentials will still be in keychain and you can retrieve them when user returns to the app.
EDIT: I think I must add one more thing..If your login logic takes time (like you login using web request or something), put the login logic code in your Login ViewController rather than ApplicationDelegate, and use any Activity Indicator during auto login process.
EDIT : I edited the entire answer, replaced NSUserDefault with Keychain. This thread explains why.
To answer the question: if you want to auto-login with keychain data, use the free framework "SFHFKeychainUtils". It saves username, password and servicename in keychain. if you want to retrieve it, just save the username in NSUserDefaults and you can get the password with ease.
Here we go:
SiFi HiFi Framework: https://github.com/ldandersen/scifihifi-iphone/tree/master/security
SiFi Hifi Framework (ARC compatible): https://stackoverflow.com/a/10348964/1011125
How to use SFHFKeychainUtils: http://gorgando.com/blog/technology/iphone_development/simple-iphone-tutorial-password-management-using-the-keychain-by-using-sfhfkeychainutils