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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top