100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > ios mysql注册登录界面_iOS+PHP实现登录功能

ios mysql注册登录界面_iOS+PHP实现登录功能

时间:2019-05-07 14:31:24

相关推荐

ios mysql注册登录界面_iOS+PHP实现登录功能

近期在做app开发的时候,因为要用到app登录功能,就自己写了个简单的iOS+PHP实现登录功能的demo,经过运行能够通过登录测试。

在开发过程中,也是碰到了各种各样的问题,经过不断的调试和改变方法,终于将所有的坑都基本上填满了,因此,将最终完整版的代码及相关流程记录在此,供自己及其它需要的人查阅使用。

一、一些约定条件

Mac OS真的是一个太太太封闭的系统环境了,封闭到我已经测试了N中办法,都没办法成功搭建后台服务器——不管是使用集成软件(如MAMP或者XAMPP),还是自行下载MySQL和MyAdmin客户端安装。有的时候Apache无法正常启动,有时候MySQL又故障掉了,更悲哀的是,真机测试时,客户端上输入内容后,无法正常与服务器通信!逼不得已,就只能放弃了,最终采用Windows的WIN7系统的电脑做后台服务器,然后与测试用的手机、编程用的Mac电脑处于同一无线局域网下。==如果哪位同仁能告知如何在MacBook上搭建后台服务器且能正常工作,欢迎不吝赐教,鄙人万分感激!==

当在装有WIN 7系统的电脑上配置服务器时,我使用的是WAMP集成软件,数据库和表的编辑操作使用的是SQLyog软件,这样可以有效的创建、修改表的内容。==注意,在WIN7的电脑上搭建完后台并创建好数据库之后,还需要进行局域网的配置工作,这样才能让处于同一局域网下的设备(如手机)连接到这台电脑及后台==。这个方法我也忘了,所以需要您和其他做PHP后台开发的同仁咨询。==如果您已经知道怎么做了,也欢迎不吝赐教,我好记录在本文章中,供更多人的来学习==。

一些约定条件如下

[x] 手机客户端能成功连接后台服务器,并与后台服务器进行数据交互

[x] 密码为原始输入的字符串,不经过MD5等加密方式的加密(正常开发时,请务必进行加密处理)

[x] 传输方式选择GET传输(为了安全起见,最好使用POST传输方式)

[x] 登录账号只选择手机号(正常开发时,登录的账号可能还有email或者用户名)

二、数据库和表的创建及初始化

使用SQLyog或者phpMyAdmin创建一个名为testAppDatabase的数据库,“基字符集”选择“utf8”,“数据库排序规则”选择“utf8_general_ci”,如下图所示(图像截取的是使用SQLyog软件创建数据库的情况,使用phpMyAdmin类似):

然后,在testAppDatabase数据库下,新建一个名为userInformationTable的表,“引擎”选择“InnoDB”,“字符集”选择“utf8”,“核对”选择“utf8_general_ci”,最后创建列名及每一列对应的数据类型以及是否可以为空等,并设置userID为主键、正数、自增,如下图所示(图像截取的是使用SQLyog软件创建表的情况,使用phpMyAdmin类似):

正常情况下,每一列都最好设置为“非空”,如果用户没有输入,那么可以默认使用“N/A”等填充,等用户输入了当前列对应的内容了,再替换掉“N/A”即可。

因为我们是做登录模块的验证,没有经过注册,因此,数据库中是没有信息的。我们可以手动先填写一些信息,供测试使用。填写好的内容如下图所示(使用的phpMyAdmin客户端插入的数据)

==注意,此时的密码是完全的明文密码,未进行任何加密,这主要是为了测试方便使用,正常开发时,请务必将保存到数据库中的密码进行加密处理。==

至此,数据库相关的“配置”就处理完了,下面是php代码相关的内容。

三、php代码

在php代码中,我们主要完成的是接收客户端传输过来的数据,并将数据与数据库进行匹配验证,一般验证的内容有两点:

[x] 用户输入的账号是否存在

[x] 用户输入的账号存在的情况下,账号和密码是否与数据库中的一一匹配

因此,我们的php代码主要就是围绕这两个逻辑来编写。

首先,编写数据库连接代码,并保存到其它用户读取不到的位置。

对php有一些了解的人应该知道,保存在htddoc路径(对于使用WAMP集成的环境来说,就是www文件夹下,如下图)下的文件,是可以被浏览器通过输入网址的方式读取到的,如果将登录数据库使用的账户和密码信息放到这个文件夹下,那么数据库是非常不安全的。

因此,我们通常将连接数据库需要的php代码单独编写并保存为“.php”格式的文件,然后将这个文件放置在与“www”同级的位置,如下图所示的“connectionToDB.php”文件。

使用php编辑器编辑“connectionToDB.php”文件,写入的代码如下:

connectionToDB.php

$dbc = mysqli_connect('192.168.1.101', 'root', '你设置的登录数据库的密码', 'testAppDatabase') or die("连接失败:".mysql_error());

//连接数据库的格式通常为

//$dbc = mysqli_connect(hostname, 登录账号, 登录密码, 数据库的名称) or die("连接失败:".mysql_error());

//hostname:一般是localhost,也常设置为作为后台的电脑的IP地址,查询的方法是“运行->cmd->ipconfig /all”,在控制台中找到IPv4地址。

//对于局域网,这个IP地址可能会不断的变化,因此,如果没有做IP固化的操作,每次使用后台服务器时,最好都加纳差一下这个IP地址,然后将“connectionToDB.php”中的IP地址换为正在使用的地址

//登录账号:一般是根用户root。如果不使用根用户,就使用数据库拥有者为你开辟的用户名和密码

//登录密码:对应登录账号的密码

//数据库名称:要连接的数据库的名称。一般一个产品只有一个数据库,该数据库中有很多的表

?>

==注意:php代码的编写,一定要使用utf-8的编码格式,这点要切记。下面提到的php文件均采用这种编码格式,将不再赘述。==

接着,编写和登录验证相关的php代码,将其保存为“login.php”文件并保存到www目录下,如下图所示:

“www”目录就想到于在浏览器中输入的localhost或者192.168.1.101这个IP地址,所以能看到,我们要编写的“login.php”在下两级目录下,知道这点这对于我们编写“login.php”文件中的某些代码是有必要的。

login.php

header('Content-type:text/html;charset=utf-8'); //代码的方式设置编码方式

require_once('../../../connectionToDB.php');

//一个"../"代表一级目录,

//因为我们的“connectionToDB.php”文件与“www”文件夹在同一级目录下

//从“login.php”追溯“connectionToDB.php”需要进过三级目录,所以需要三个"../"

$postedData = $_REQUEST; //$_REQUEST既可以获取到通过POST方式传输的数据,也可以获取到通过GET方式传输的数据

//获取用户输入的账号的形式:手机号、邮箱地址还是一般用户名

$userAccountType = $postedData['Account_Type'];

//获取用户输入的账号和密码

$userAccount = $postedData['User_Account'];

$userPassword = $postedData['User_Password'];

//根据账户形式获取对应的账号内容,用于后面的比对

//是否账号是否存在的标签以及是否登录成功的标签

$accountBeingOrNotFlag = "0"; //0代表账号不存在,1代表账号存在

$loginOKOrNotFlag = "0"; //0代表登录失败,1代表登录成功

switch ($userAccountType) {

case "Telephone": //账号是手机号

$q = "SELECT * FROM userinformationtable WHERE UserTelephoneNumber = $userAccount"; //查询数据库有没有这个手机号

$r = @mysqli_query($dbc, $q);

$rows = @mysqli_num_rows($r); //查询到的信息的行数,如果行数不是0,说明查询到了信息

if($rows) {

//行数不是0,说明有这个手机号,设置标签的值为1

$accountBeingOrNotFlag = "1"; //账号存在

//查询账号和密码是否匹配

$qA = "SELECT * FROM userinformationtable WHERE UserTelephoneNumber = '$userAccount' and UserPassword = '$userPassword'";

$rA = @mysqli_query($dbc, $qA);

$rowsA = @mysqli_num_rows($rA);

if($rowsA) {

//行数不是0,说明账号和密码匹配,设置标签值为1,登录成功

$loginOKOrNotFlag = "1";

}else {

//行数是0,说明账号和密码不匹配,设置标签值为0,登录失败

$loginOKOrNotFlag = "0";

}

}else {

//行数是0,说明账号不存在,设置标签值为0

$accountBeingOrNotFlag = "0";

}

//将标签值保存到数组中,然后将其传递给客户端,客户端根据标签值判断对应的操作逻辑

$returnArr = array("accountBeingOrNotFlag" => $accountBeingOrNotFlag, "loginOKOrNotFlag" => $loginOKOrNotFlag);

//下面的两行代码是方便测试使用,即将我们测试的一些内容保存到一个.log文件中,然后通过查看这个文件,看结果是否是我们想要的

$dccc = print_r($returnArr, true);

file_put_contents('C://Users/Administrator/Desktop/zj.log', $dccc);

//关闭数据库连接

mysqli_close($dbc);

//将要传递给客户端的结果信息通过json编码的形式输出

echo json_encode($returnArr);

break;

//下面的代码注释和上面的这个case里面的类似,不再赘述

case "EmailAddress":

$q = "SELECT * FROM userinformationtable WHERE UserEmailAddress = $userAccount";

$r = @mysqli_query($dbc, $q);

@$rows = mysql_num_rows($r);

if($rows) {

$accountBeingOrNotFlag = "1"; //账号存在

$qA = "SELECT * FROM userinformationtable WHERE UserEmailAddress = '$userAccount' and UserPassword = '$userPassword'";

//$qA = "SELECT * FROM userinformationtable WHERE UserTelephoneNumber = 13240132824 and UserPassword = l19880226";

$rA = @mysqli_query($dbc, $qA);

$rowsA = @mysqli_num_rows($rA);

if($rowsA) {

$loginOKOrNotFlag = "1"; //登录成功

}else {

$loginOKOrNotFlag = "0"; //登录失败

}

}else {

$accountBeingOrNotFlag = "0"; //账号不存在

}

$returnArr = array("accountBeingOrNotFlag" => $accountBeingOrNotFlag, "loginOKOrNotFlag" => $loginOKOrNotFlag);

mysqli_close($dbc);

echo json_encode($returnArr); //输出json格式

break;

case "NormalName":

$q = "SELECT * FROM userinformationtable WHERE UserNormalName = $userAccount";

$r = @mysqli_query($dbc, $q);

@$rows = mysql_num_rows($r);

if($rows) {

$accountBeingOrNotFlag = "1"; //账号存在

$qA = "SELECT * FROM userinformationtable WHERE UserNormalName = '$userAccount' and UserPassword = '$userPassword'";

$rA = @mysqli_query($dbc, $qA);

$rowsA = @mysqli_num_rows($rA);

if($rowsA) {

$loginOKOrNotFlag = "1"; //登录成功

}else {

$loginOKOrNotFlag = "0"; //登录失败

}

}else {

$accountBeingOrNotFlag = "0"; //账号不存在

}

$returnArr = array("accountBeingOrNotFlag" => $accountBeingOrNotFlag, "loginOKOrNotFlag" => $loginOKOrNotFlag);

mysqli_close($dbc);

echo json_encode($returnArr); //输出json格式

break;

}

?>

好了,和登录有关的php代码已经编写完成了,下面就开始编写iOS客户端的代码。

四、iOS客户端

iOS客户端的代码,我们将采用MVC的架构来编写。

可能有人会问,只是一个demo,为什么不将M也合并到V中一起写呢?这个就和我在文章开头提到的坑有关了。

我们先来看一个将MVC写在一个viewController中的例子

将MVC写在一个viewController中的例子

我们随便新建一个基于单视图的工程,然后在ViewController.m文件中编写如下代码:

ViewController.m的viewDidLoad方法中

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

NSURL *url = [NSURL URLWithString:@"http://192.168.1.101/testApp/Login/login.php"];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

//设置请求方式 POST

request.HTTPMethod = @"POST";

//设置请求的超时时间

request.timeoutInterval = 60;

request.HTTPBody = [[NSString stringWithFormat:@"User_Account=%@&User_Password=%@&Account_Type=%@",@"13542138562",@"testApp123456", @"Telephone"] dataUsingEncoding:NSUTF8StringEncoding];

NSURLSession *session = [NSURLSession sharedSession];

//4 创建网络任务 NSURLSessionTask

//通过网络会话 来创建数据任务

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

NSLog(@"网络请求完成");

NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"data = %@", data);

NSLog(@"result = %@", result);

_str = result;

NSLog(@"1.2_str = %@", _str);

// dispatch_async(dispatch_get_main_queue(), ^{

//

// // do something

//

//

// _str = result;

//

// NSLog(@"1.2_str = %@", _str);

//

//

// });

}];

//5 发起网络任务

[dataTask resume];

NSLog(@"_str = %@", _str);

}

这段代码本来是想完成的工作是:将登陆的信息传递给后台之后,后台进行验证,并将验证的结果(没有账号、账号密码不匹配、账号密码匹配)传回给客户端,然后由客户端根据返回回来的标签值做响应的操作。但是运行这段代码之后,通过断点调试,会发现,dataTaskWithRequest:completionHandler:并没有按照顺序执行,而是直接跳过,然后执行了[dataTask resume];方法,接着就是NSLog函数输出_str的值,会发现值是空的。当viewDidLoad代码块全部执行完毕后(即执行到最后一个右大括号}),才会执行dataTaskWithRequest:completionHandler:代码块中的内容。虽然此后会更新_str的值,但此时其实客户端已经接收了第一次的_str的值了,如果不做其它的工作,我们是很难得到想要的结果了。

后来经过多次的调试、验证,最终才发现,使用通知可以解决这个问题。这也就是为啥我要把M单独写的原因:我们可以在M里面发送通知,然后在view里面注册通知和实现通知的方法。

我们分别创建一个继承于NSObject的RegisterAndLoginModel文件,一个继承于UIViewController的LoginViewController文件,以及一个继承于UIView的LoginView文件。

编写RegisterAndLoginModel文件

RegisterAndLoginModel.h

#import

@interface RegisterAndLoginModel : NSObject

- (void)checkTheUserAccount : (NSString*)userAccount andPassword : (NSString*)userPassword withAccountType : (NSString*)accountType;

@end

RegisterAndLoginModel.m

#import "RegisterAndLoginModel.h"

@implementation RegisterAndLoginModel

//GET方式提交数据

- (void)checkTheUserAccount : (NSString*)userAccount andPassword : (NSString*)userPassword withAccountType : (NSString*)accountType {

NSMutableDictionary *returnDictionary = [[NSMutableDictionary alloc]initWithCapacity:2];

NSLog(@"userAccount = %@, userPassword = %@, accountType = %@", userAccount, userPassword, accountType);

//1.构造URL网络地址

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.101/testApp/Login/login.php?User_Account=%@&User_Password=%@&Account_Type=%@",userAccount,userPassword, accountType]];

//2.构造网络请求对象 NSURLRequest

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

NSLog(@"request = %@", url);

//3.设置请求方式 GET

request.HTTPMethod = @"GET";

//设置请求的超时时间

request.timeoutInterval = 60;

NSURLSession *session = [NSURLSession sharedSession];

//4 创建网络任务 NSURLSessionTask。通过网络会话 来创建数据任务

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

NSLog(@"网络请求完成");

NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];

NSLog(@"接收到的数据为%@",jsonDic);

[returnDictionary setObject:jsonDic forKey:@"returnDictionaryKey"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"loginStatusInformationDictionary" object:returnDictionary];

}];

//5.发起网络任务

[dataTask resume];

}

编写LoginViewController文件

LoginViewController.h

#import

#import "LoginView.h"

#import "RegisterAndLoginModel.h"

@protocol LoginViewControllerDelegate

@optional

- (void)goToRegisterViewController;

- (void)loginSucceed;

@end

@interface LoginViewController : UIViewController

{

NSString *accountTypeString;

}

@property (assign, nonatomic) idloginViewControllerDelegate;

@property (strong, nonatomic) RegisterAndLoginModel *registerAndLoginModel;

@property (strong, nonatomic) LoginView *loginView;

@end

LoginViewController.m

#import "LoginViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

int accountIsNotNULL = 0; //账号是否为空

int loginPasswordIsOK = 0; //密码格式是否正确

int loginBtnPressedNumbers = 0; //登录按钮累计点击次数

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view.

//添加通知,监测后台服务器返回的标签值

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getTheLoginStatusDiecitonary:) name:@"loginStatusInformationDictionary" object:nil];

_loginView = [[LoginView alloc]initTheLoginViewWithFrame:CGRectMake(0, 0, deviceScreenWidth, deviceScreenHeight)];

_loginView.loginViewDelegate = self;

[_loginView.goToRegisterButton addTarget:self action:@selector(goToRegisterButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

[_loginView.findPasswordButton addTarget:self action:@selector(findPasswordButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:_loginView];

_registerAndLoginModel = [[RegisterAndLoginModel alloc]init];

}

- (void)loginButtonPressed : (UIButton*)sender {

NSLog(@"点击了登录");

NSLog(@"loginBtnPressedNumbers = %i", loginBtnPressedNumbers);

//首先判断用户输入的账号的类型

if(![self checkPhoneNumInputWithString:_loginView.loginAccountTextField.text]) {

//不是手机号

if(![self isEmailAddress:_loginView.loginAccountTextField.text]) {

//也不是邮箱地址

accountTypeString = @"NormalName";

}else {

//是邮箱地址

accountTypeString = @"EmailAddress";

}

}else {

//是手机号

accountTypeString = @"Telephone";

}

[_registerAndLoginModel checkTheUserAccount:_loginView.loginAccountTextField.text andPassword:_loginView.loginPasswordTextField.text withAccountType:accountTypeString];

loginBtnPressedNumbers += 1;

}

- (void)goToRegisterButtonPressed : (UIButton*)sender {

NSLog(@"去注册");

[_loginViewControllerDelegate goToRegisterViewController];

}

- (void)findPasswordButtonPressed : (UIButton*)sender {

NSLog(@"找回密码");

}

#pragma mark - 实现LoginViewDelegate中的方法

- (void)getTheInputStringInLoginViewFromTheTextField : (NSString*)inputString withTextFieldTag : (NSInteger)tag {

if(tag == 20001) {

if (inputString.length > 0) {

accountIsNotNULL = 1;

}else {

accountIsNotNULL = 0;

}

}else {

if((inputString.length >= 8) && (inputString.length <= 20)) {

loginPasswordIsOK = 1;

}else {

loginPasswordIsOK = 0;

}

}

if(accountIsNotNULL == 1 && loginPasswordIsOK == 1) {

[_loginView.loginButton addTarget:self action:@selector(loginButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

_loginView.loginButton.alpha = 1.0;

[_loginView.loginButton setBackgroundColor:[UIColor redColor]];

[_loginView.loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

[_loginView.loginButton setUserInteractionEnabled:YES];

}else {

[_loginView.loginButton setBackgroundColor:[UIColor colorWithRed:211/255.0 green:211/255.0 blue:211/255.0 alpha:1.0]];

[_loginView.loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

[_loginView.loginButton setUserInteractionEnabled:NO];

}

}

#pragma mark - 使用正则表达式判断手机号格式是否正确

-(BOOL)checkPhoneNumInputWithString : (NSString*)telephoneString {

NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";

NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";

NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";

NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";

// NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";

NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];

NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];

NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];

NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];

BOOL res1 = [regextestmobile evaluateWithObject:telephoneString];

BOOL res2 = [regextestcm evaluateWithObject:telephoneString];

BOOL res3 = [regextestcu evaluateWithObject:telephoneString];

BOOL res4 = [regextestct evaluateWithObject:telephoneString];

if (res1 || res2 || res3 || res4 ) {

return YES;

}else {

return NO;

}

}

#pragma mark - 正则表达式判断邮箱格式是否正确

- (BOOL)isEmailAddress:(NSString*)inputEmailAddress

{

NSString* emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

return [emailTest evaluateWithObject:inputEmailAddress];

}

#pragma mark 实现通知方法

- (void)getTheLoginStatusDiecitonary :(NSNotification*) notification {

NSMutableDictionary *resultDictionary = [notification object];

NSLog(@"resultDictionary = %@", resultDictionary);

NSDictionary *judgmentDictionary = [resultDictionary objectForKey:@"returnDictionaryKey"];

NSLog(@"judgmentDictionary = %@", judgmentDictionary);

if([[judgmentDictionary objectForKey:@"accountBeingOrNotFlag"] isEqualToString:@"0"]) {

//账号不存在,提示用户是否去注册

NSLog(@"对不起,账号不存在");

//此处的操作一定要回到主线程操作,否则程序会崩溃,警告框弹不出来

dispatch_async(dispatch_get_main_queue(), ^{

// do something

UIAlertController *accountNotBeingAlert = [UIAlertController alertControllerWithTitle:@"账号不存在" message:@"对不起,您输入的账号不存在,是否前去注册?" preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];

UIAlertAction *goToRegisterAction = [UIAlertAction actionWithTitle:@"去注册" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) {

//进入注册界面

[_loginViewControllerDelegate goToRegisterViewController];

}];

[accountNotBeingAlert addAction:cancelAction];

[accountNotBeingAlert addAction:goToRegisterAction];

[self presentViewController:accountNotBeingAlert animated:YES completion:nil];

});

}else {

//账号存在

//判断账号和密码是否匹配

if([[judgmentDictionary objectForKey:@"loginOKOrNotFlag"] isEqualToString:@"0"]) {

//账号和密码不匹配

NSLog(@"账号和密码不匹配,请重新输入");

if(loginBtnPressedNumbers > 2) {

if([accountTypeString isEqualToString:@"Telephone"]) {

//用户输入的账号是手机号,显示获取短信验证码

//短信验证码一段时间内只能获取三次,如果超过三次,那么显示图形验证码

//更新界面元素的时候,也需要回到主线程,否则程序就崩溃或者界面UI更新错位

dispatch_async(dispatch_get_main_queue(), ^{

// do something

_loginView.verificationCodeTextField.hidden = NO;

_loginView.loginButton.frame = CGRectMake(20, 345, deviceScreenWidth - 40, 50);

_loginView.goToRegisterButton.frame = CGRectMake(20, 405, deviceScreenWidth /2 - 20, 25);

_loginView.findPasswordButton.frame = CGRectMake(deviceScreenWidth / 2, 405, deviceScreenWidth /2 - 20, 25);

});

}else {

//账号是邮箱地址或者一般用户名,显示图形验证码

}

}

}else {

//账号和密码匹配,登录成功

//登录成功后将登录状态信息保存到NSUserDefaults中,供程序调用

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setObject:_loginView.loginAccountTextField.text forKey:@"accountStr"];

[defaults setObject:_loginView.loginPasswordTextField.text forKey:@"passwordStr"];

[defaults setObject:@"isLogin" forKey:@"isLoginStr"];

[defaults synchronize];

[_loginViewControllerDelegate loginSucceed];

}

}

}

@end

编写LoginView文件

LoginView.h

#import

@protocol LoginViewDelegate

- (void)getTheInputStringInLoginViewFromTheTextField : (NSString*)inputString withTextFieldTag : (NSInteger)tag;

@end

@interface LoginView : UIView

@property (assign, nonatomic) idloginViewDelegate;

@property (strong, nonatomic) UITextField *loginAccountTextField;

@property (strong, nonatomic) UITextField *loginPasswordTextField;

@property (strong, nonatomic) UITextField *verificationCodeTextField;

@property (strong, nonatomic) UIButton *getVerificationCodeButton;

@property (strong, nonatomic) UIButton *loginButton;

@property (strong, nonatomic) UIButton *goToRegisterButton;

@property (strong, nonatomic) UIButton *findPasswordButton;

- (id)initTheLoginViewWithFrame : (CGRect)frame;

@end

LoginView.m

#import "LoginView.h"

#import "UIImage+CircleImageView.h" //圆形头像

@implementation LoginView

- (id)initTheLoginViewWithFrame : (CGRect)frame {

self = [super initWithFrame:frame];

if(self) {

//账号输入框

_loginAccountTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, 120, deviceScreenWidth - 40, 55)];

[_loginAccountTextField setClearButtonMode:UITextFieldViewModeWhileEditing];

_loginAccountTextField.placeholder = @"用户名/邮箱地址/手机号";

_loginAccountTextField.keyboardType = UIKeyboardTypeDefault;

_loginAccountTextField.borderStyle = UITextBorderStyleRoundedRect;

_loginAccountTextField.tag = 20001;

[self addSubview:_loginAccountTextField];

UIImageView *accountTextFieldLeftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_loginAccountTextField.frame.origin.x + 30, _loginAccountTextField.frame.origin.y +5 , 45, 45)];

accountTextFieldLeftImageView.image = [UIImage imageNamed:@"Account"];

_loginAccountTextField.leftView = accountTextFieldLeftImageView;

_loginAccountTextField.leftViewMode = UITextFieldViewModeAlways;

//密码输入框

_loginPasswordTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, 190, deviceScreenWidth - 40, 55)];

[_loginPasswordTextField setClearButtonMode:UITextFieldViewModeWhileEditing];

_loginPasswordTextField.placeholder = @"输入8~20位字符的密码";

_loginPasswordTextField.keyboardType = UIKeyboardTypeDefault;

_loginPasswordTextField.borderStyle = UITextBorderStyleRoundedRect;

_loginPasswordTextField.secureTextEntry = YES;

_loginPasswordTextField.tag = 20002;

[self addSubview:_loginPasswordTextField];

UIImageView *passwordTextFieldLeftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_loginPasswordTextField.frame.origin.x + 10, _loginPasswordTextField.frame.origin.y + 5, 40, 40)];

passwordTextFieldLeftImageView.image = [UIImage imageNamed:@"password"];

_loginPasswordTextField.leftView = passwordTextFieldLeftImageView;

_loginPasswordTextField.leftViewMode = UITextFieldViewModeAlways;

//验证码输入框

_verificationCodeTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, 260, deviceScreenWidth - 40, 55)];

[_verificationCodeTextField setClearButtonMode:UITextFieldViewModeWhileEditing];

_verificationCodeTextField.placeholder = @"输入4位短信验证码";

_verificationCodeTextField.keyboardType = UIKeyboardTypeDefault;

_verificationCodeTextField.borderStyle = UITextBorderStyleRoundedRect;

_verificationCodeTextField.tag = 20003;

_verificationCodeTextField.hidden = YES;

[self addSubview:_verificationCodeTextField];

UIImageView *verificationCodeFieldLeftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_verificationCodeTextField.frame.origin.x + 30, _verificationCodeTextField.frame.origin.y +5 , 45, 45)];

verificationCodeFieldLeftImageView.image = [UIImage imageNamed:@"Account"];

_verificationCodeTextField.leftView = verificationCodeFieldLeftImageView;

_verificationCodeTextField.leftViewMode = UITextFieldViewModeAlways;

//登录按钮

_loginButton = [UIButton buttonWithType:UIButtonTypeCustom];

_loginButton.frame = CGRectMake(20, 275, deviceScreenWidth - 40, 50);

_loginButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

_loginButton.titleLabel.font = [UIFont systemFontOfSize:17.0];

[_loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

[_loginButton setTitle:NSLocalizedString(@"LoginButtonName", nil) forState:UIControlStateNormal];

[_loginButton setBackgroundColor:[UIColor colorWithRed:211/255.0 green:211/255.0 blue:211/255.0 alpha:1.0]];

[_loginButton setUserInteractionEnabled:NO];

[self addSubview:_loginButton];

//去注册按钮

_goToRegisterButton = [UIButton buttonWithType:UIButtonTypeSystem];

_goToRegisterButton.frame = CGRectMake(20, 335, deviceScreenWidth /2 - 20, 25);

_goToRegisterButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

_goToRegisterButton.titleLabel.font = [UIFont systemFontOfSize:14.0];

[_goToRegisterButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];

[_goToRegisterButton setTitle:NSLocalizedString(@"GoToRegisterButtonName", nil) forState:UIControlStateNormal];

[_goToRegisterButton setBackgroundColor:[UIColor clearColor]];

[self addSubview:_goToRegisterButton];

//找回密码按钮

_findPasswordButton = [UIButton buttonWithType:UIButtonTypeSystem];

_findPasswordButton.frame = CGRectMake(deviceScreenWidth / 2, 335, deviceScreenWidth /2 - 20, 25);

_findPasswordButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;

_findPasswordButton.titleLabel.font = [UIFont systemFontOfSize:14.0];

[_findPasswordButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];

[_findPasswordButton setTitle:NSLocalizedString(@"GetPasswordButtonName", nil) forState:UIControlStateNormal];

[_findPasswordButton setBackgroundColor:[UIColor clearColor]];

[self addSubview:_findPasswordButton];

//添加通知,监测输入内容

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginAccountTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:_loginAccountTextField];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginPasswordTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:_loginPasswordTextField];

}

return self;

}

#pragma mark - 实现通知的方法

- (void)loginAccountTextFieldTextDidChangeNotification:(NSNotification *)notification {

UITextField *textField = notification.object;

[self.loginViewDelegate getTheInputStringInLoginViewFromTheTextField:textField.text withTextFieldTag : textField.tag];

}

- (void)loginPasswordTextFieldTextDidChangeNotification:(NSNotification *)notification {

UITextField *textField = notification.object;

[self.loginViewDelegate getTheInputStringInLoginViewFromTheTextField:textField.text withTextFieldTag : textField.tag];

}

@end

五、一些会碰到的错误

[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread

这个问题说的是需要在主线程来完成这个工作,碰到这个问题的地方是这个示例中,如果用户输入的账户不存在,弹出来一个警告框提示用户是否要去注册的时候,如果警告框的相关代码没有在主线程中操作的话,就会有这个问题。

Main Thread Checker: UI API called on a background thread: -[UIView setHidden:]

这个提示是说部分UI的更新需要在主线程中完成,如果没有在主线程中完成这个操作,可能会有错位界面。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。