My app (like most) is going to be leveraging many remote services... so when a user authenticates themselves, I need to store their username and password (or some kind of flag) so that they don't have to authenticate all over the app.
Where is the best/quickest/easiest place to store this user data?
You can still store the username and server URL with NSUserDefaults, but Keychain services is the best idea if you're storing a password. It's part of the C-Based security framework, and there'a a great wrapper class SFHFKeychainUtils, to give it an Objective-C API.
To save:
NSString *username = @"myname";
NSString *password = @"mypassword";
NSURL *serverURL = [NSURL URLWithString:@"http://www.google.com"];
[SFHFKeychainUtils storeUsername:username andPassword:password forServiceName:[serverURL absoluteString] updateExisting:YES error:&error]
To restore:
NSString *passwordFromKeychain = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:[serverURL absoluteString] error:&error];
NSUserDefaults
Save like this:
[[NSUserDefaults standardUserDefaults] setObject:username forKey:@"username"];
[[NSUserDefaults standardUserDefaults] setObject:password forKey:@"password"];
[[NSUserDefaults standardUserDefaults] synchronize];
Fetch like this:
NSString *username = [[NSUserDefaults standardUserDefaults] stringForKey:@"username"];
NSString *password = [[NSUserDefaults standardUserDefaults] stringForKey:@"password"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With