关于钥匙串

一般使用NSUserDefaults的明文来存储用户名,使用SSKeychain来存对应的密码

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 读取用户偏好信息
    self.usernameText.text = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserNameKey];
    
    // 读取账户信息
    NSLog(@"%@", [SSKeychain allAccounts]);
    
    NSString *pwd = [SSKeychain passwordForService:kLoginKeyServiceName account:self.usernameText.text];
    self.pwdText.text = pwd;
    
    // 删除钥匙串
    [SSKeychain deletePasswordForService:kLoginKeyServiceName account:@"zhangsan"];
}


- (IBAction)login {
    NSString *username = self.usernameText.text;
    NSString *pwd = [self.pwdText.text md5String];
    
    NSLog(@"%@", pwd);
    
    NSString *urlString = @"http://10.0.1.7/login.php";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    NSString *bodyString = [NSString stringWithFormat:@"username=%@&password=%@", username, pwd];
    request.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        
        // 数据处理代码...
        NSLog(@"%@", result);
        if ([result[@"userId"] intValue] > 0) {
            [[NSUserDefaults standardUserDefaults] setObject:username forKey:kLoginUserNameKey];
            [[NSUserDefaults standardUserDefaults] synchronize];


            // 设置密码
            [SSKeychain setPassword:self.pwdText.text forService:kLoginKeyServiceName account:self.usernameText.text];
        }
    }];
}


@end

你可能感兴趣的:(工作笔记)