开发者

iPhone - Saving and Loading a user's login information from file

Hey guys, I am having a bit of a problem trying to save a user's Login (email) and password (chars/nums). These are both UITextFields of NSStrings.

I have it set up right now at the end of the view before it gets dismissed as

[email writeToFile:@"Login" atomically:YES encoding:NSUTF8St开发者_如何转开发ringEncoding error:&error];
[password writeToFile:@"Password" atomically:YES encoding:NSUTF8StringEncoding error:&error];

However, I am not sure as how to go about loading these when the view is loaded. I tried doing this at the beginning of the view loading:

NSString *email;
NSString *password;
NSError *error;
NSString *em = [[NSString alloc] initWithContentsOfFile:@"Login" encoding:NSUTF8StringEncoding error:&error]; 
NSString *pass = [[NSString alloc] initWithContentsOfFile:@"Password" encoding:NSUTF8StringEncoding error:&error];
if (error == nil) {
   userEmail.text = em;
   userPassword.text = pass; 
}

email = userEmail.text;
password = userPassword.text;

However, I cannot actually get the data in these two files..is it because I have to have the full path to the file? Also, is there a way to save these both into one file (NSMutableDictionary)? Any advice would be great!!

Alex


You should not store a user's credentials in plain text in a file. It can easily be read if the phone is ever lost or hacked.

A much better approach is to store the information securely in the iPhone Keychain. This will handle the encryption/decryption for you, and is more secure than what you're likely to write yourself.

One library that will make working with the Keychain easier is SFHFKeychainUtils. This will give you an abstraction that works on the Simulator as well as the device.


You might want to look at NSUserDefaults instead, but to answer your question you might want to specify the path.

Get Path:


NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/Login", docDir];

Save:


[em writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

Load:

NSString *em = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];

Don't forget to [em release] to avoid memory leaks!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜