在点击事件中进行登录操作
- (IBAction)btnLoginDidClick:(UIButton *)sender {
// 如果两个文本框均不为空,则进行登录操作
if (self.userName.text.length && self.password.text.length) {
// 1. 创建请求
NSString *urlString = @"http://www.easck.com// 设置请求参数
NSString *body = [NSString stringWithFormat:@"username=%@&password=%@", self.userName.text, self.password.text];
// 将字符串转为二进制数据
NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
// 设置请求主体(二进制数据)
request.HTTPBody = bodyData;
// 2. 发送请求
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 打印请求结果
NSLog(@"data:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
// 判断是否登录成功
if (data && !error) {
NSLog(@"网络请求成功!");
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if (dict[@"userID"]) {
[self saveLocalUserInfo];
}
//跳转到app主界面,在主线程中发送通知
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
});
} else {
NSLog(@"网络请求失败!");
}
}] resume];
} else {
NSLog(@"用户名或密码不能为空!");
}
}
C. 实现页面间跳转
在AppDelegate.m文件中利用通知设置页面的跳转
切换的主方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 1. 注册登录成功的通知观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"loginSuccess" object:nil];
// 2. 注册登录成功的通知观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutSuccess) name:@"logoutSuccess" object:nil];
// 每次app打开后,应该展示给用户哪个界面
// 3. 利用偏好设置中用户保存的信息来判断用户的登录状态
NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:kUserNameKey];
NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:kPasswordKey];
if (userName && password) {
// 显示app 主界面
[self loginSuccess];
} else {
[self logoutSuccess];
}
return YES;
}
登录成功
- (void)loginSuccess {
NSLog(@"登录成功!");
// 获取主界面
UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
// 切换控制器
self.window.rootViewController = mainSb.instantiateInitialViewController;
}
注销成功










