Question

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?

Was it helpful?

Solution

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];

OTHER TIPS

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"];

Storing secure data in an insecure file (user defaults) isn't usually a good idea. Look into Keychain Services, which encrypts sensitive login information and such.

http://developer.apple.com/library/mac/#documentation/Security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top