开发者

iPhone: Save user data in plist, SQLite or cookie?

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 authentic开发者_StackOverflowate 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜