結合MD5加密的方式,簡單介紹一下登錄保存賬號密碼的邏輯
前言:
1."NSString+Hash.h"是一個MD5加密的分類
2.這里使用了Apache搭建了一個簡單的本地服務器來進行演示
3.使用NSURLConnection演示發(fā)送登錄請求,請求字段匹配(userId.intValue == 1),代表登錄成功,此時將真確的賬號密碼保存至偏好設置
4.首次登錄,對密碼進行一次MD5加密,將加密后的密碼發(fā)送至服務器
5.設置一個標識用于判斷是否為首次登錄,首次登錄對密碼進行加密
6.iOS7后蘋果加入了鑰匙串的功能,這里將信息保存至沙盒演示
#import "ViewController.h"
#import "NSString+Hash.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *tf_username;
@property (weak, nonatomic) IBOutlet UITextField *tf_password;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//從沙盒獲取用戶名和密碼
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *username = [defaults objectForKey:@"username"];
NSString *password = [defaults objectForKey:@"password"];
//給控件賦值
self.tf_username.text = username;
self.tf_password.text = password;
}
- (IBAction)loginBtnClick:(id)sender {
//獲取用戶名和密碼
NSString *username = self.tf_username.text;
NSString *password = self.tf_password.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSNumber *flag = [defaults objectForKey:@"flag"];
//如果是第一次
if (!flag.boolValue) {
password = [password md5String];
//更改標識
[defaults setObject:@YES forKey:@"flag"];
[defaults synchronize];
}
//1. URL
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login.php"];
//2. 根據(jù)URL創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//設置請求體的數(shù)據(jù)
NSString *string = [NSString stringWithFormat:@"username=%@&password=%@",username,password] ;
//設置請求體
request.HTTPBody = [string dataUsingEncoding:NSUTF8StringEncoding];
//設置請求方法
request.HTTPMethod = @"POST";
//3.建立連接發(fā)送請求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError != nil || data == nil) {
NSLog(@"請求失敗");
}
//數(shù)據(jù)解析/反序列化
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSNumber *userId = [dict objectForKey:@"userId"];
//判斷是否登錄成功
if (userId.intValue == 1) {
//保存用戶名
[defaults setObject:username forKey:@"username"];
[defaults setObject:password forKey:@"password"];
//同步一下, iOS8以后不需要調用,系統(tǒng)會自動調用
[defaults synchronize];
}
NSLog(@"%@",dict);
}];
}
@end