将账号密码用Plist文件保存在本地

      在IOS项目的开发中,登陆的时候需要输入账号密码,但是每次登陆如果老是要输入账号密码,用户会很烦躁的,所有为了考虑用户体验,我们会做一个记住账号密码的功能。其基本原理就是用户第一次输入账号密码之后,我们就把账号密码保存在本地,当然前提是这个账号密码是正确的,总体来说还是挺简单的,不如直接看代码吧。


#import <UIKit/UIKit.h>

@interface LoadViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextField *textAccount;
@property (weak, nonatomic) IBOutlet UITextField *textPassword;

@end

//把账号和密码写入plist
- (void)writeToPlist {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * path = [paths objectAtIndex:0];
    NSString *Files = @"Account";
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString *filePath =[NSString stringWithFormat:@"%@/%@",path,Files];
    if (![fm fileExistsAtPath:filePath]) {
        [fm createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString * docDir = [filePath stringByAppendingPathComponent:@"account.plist"];
    NSMutableDictionary * loaddic = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.textAccount.text,@"name",self.textPassword.text,@"password", nil];
    [loaddic writeToFile:docDir atomically:YES];
}

//从plist文件中读取账号和密码
- (NSMutableDictionary *)readFromPlist {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * path = [paths objectAtIndex:0];
    NSString *Files = @"Account";
    NSFileManager * fm = [NSFileManager defaultManager];
    NSString *filePath =[NSString stringWithFormat:@"%@/%@",path,Files];
    if (![fm fileExistsAtPath:filePath]) {
        [fm createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString * docDir = [filePath stringByAppendingPathComponent:@"account.plist"];
    NSMutableDictionary *loaddic = [NSMutableDictionary dictionaryWithContentsOfFile:docDir];
    NSString *name =[loaddic objectForKey:@"name"];
    NSString *password =[loaddic objectForKey:@"password"];
    self.textAccount.text = name;
    self.textPassword.text = password;
    return loaddic;
}

这个是最主要的代码,还有一些调用的方法,就自个儿去写吧。

你可能感兴趣的:(密码,plist)