IOS短信验证码实现


本验证码是基于sharSDK的一个实现,需要在项目中导入shareSDK框架

 //

//   JLRegisterViewController.m
//   短信验证
//
//   Created by 袁俊亮 on 15/6/26.
//   Copyright (c) 2015年 qiji. All rights reserved.
//

#import  " QJRegisterViewController.h "
#import  " WXApi.h "
#import <SMS_SDK/SMS_SDK.h>

#define statusBarHeight 20
#define textFieldMargin 10  //  两个输入框之间的间距
#define timeCount 60  // 倒计时长

static  int count =  0;

@interface QJRegisterViewController()<UIAlertViewDelegate,WXApiDelegate, UITextFieldDelegate>
{
    NSTimer* _showRepeatButtonTimer;  //  显示重新发送按钮倒计时
    NSTimer* _updateTime;  //  更新倒计时label
    
    UIAlertView *_notGetSMSAlert;  // 没有搜到验证码重新发送弹窗
    UIAlertView *_backButtonClickAlert;  // 点击返回按钮弹窗
}


@property(nonatomic, weak) UITextField *telField;  // 手机号码
@property (nonatomic, weak) UITextField *verifyField;  //  验证码
@property (nonatomic, weak) UIButton *loginBtn;  // 登录按钮
@property(nonatomic,strong) UITextField* areaCodeField;  // 区号
@property (nonatomic, weak) UIButton *icon;  //  头像
@property (nonatomic, weak) NSString *str;  //  alert提示信息
@property (nonatomic, weak) UIButton *verifyRightView;  // 获取验证码按钮

@end

@implementation QJRegisterViewController

- ( void)viewDidLoad
{
     //  配置
    _areaCodeField.text=[NSString stringWithFormat: @" +%@ ",@ 86];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithName: @" background "]];
    
     //  布局子控件
    [self setupSubViews];
}

/* *
 *  布局子控件
 
*/
- ( void)setupSubViews
{
#warning 这里需要根据图片的大小大小来动态确定各控件的frame。这里还没有设置icon的图片
     //  创建LOGO
    CGFloat logoX = self.view.width *  0.5 - self.icon.currentBackgroundImage.size.width *  0.5;
    CGFloat logoY =  100;
    CGFloat logoW = self.icon.currentBackgroundImage.size.width;
    CGFloat logoH = self.icon.currentBackgroundImage.size.height;
    UIButton *icon = [[UIButton alloc] initWithFrame:CGRectMake(logoX, logoY, logoW, logoH)];
    icon.backgroundColor = [UIColor blueColor];
    [self.view addSubview:icon];
    self.icon = icon;
    
     //  创建手机号码输入框
    CGFloat telFieldX = self.view.width *  0.5 -  115;
    CGFloat telFieldY = self.icon.height + self.icon.currentBackgroundImage.size.height +  84;
    CGFloat telFieldW =  230;
    CGFloat telFieldH =  40;
    UITextField *telField = [[UITextField alloc] initWithFrame:CGRectMake(telFieldX, telFieldY, telFieldW, telFieldH)];
    telField.placeholder =  @" 请输入手机号码 ";
    [self creatTextFieldLeftViewWithTextfield:telField andLeftViewImageName: @" tel_leftIcon "];
    self.telField = telField;
    
     //  创建验证码输入框
    CGFloat verifyFieldX = telFieldX;
    CGFloat verifyFieldY = telFieldY + telFieldH + textFieldMargin;
    CGFloat verifyFieldW = telFieldW;
    CGFloat verifyFieldH = telFieldH;
    UITextField *verifyField = [[UITextField alloc] initWithFrame:CGRectMake(verifyFieldX, verifyFieldY, verifyFieldW, verifyFieldH)];
    verifyField.placeholder =  @" 请输入手机验证码 ";
    [self creatTextFieldLeftViewWithTextfield:verifyField andLeftViewImageName: @" verify_leftIcon "];  //  添加左边图标
    self.verifyField = verifyField;
    
     //  添加获取验证码按钮
    UIButton *verifyRightView = [[UIButton alloc] init];
    [verifyRightView setBackgroundImage:[UIImage imageWithName: @" verify_rightNormal "] forState:UIControlStateNormal];
    [verifyRightView setBackgroundImage:[UIImage imageWithName: @" verify_right_highlighted "] forState:UIControlStateHighlighted];
    [verifyRightView setTitle: @" 获取验证码 " forState:UIControlStateNormal];
    verifyRightView.font = [UIFont boldSystemFontOfSize: 10];
    verifyRightView.width = verifyRightView.currentBackgroundImage.size.width;
    verifyRightView.height = verifyRightView.currentBackgroundImage.size.height;
    verifyRightView.frame = CGRectMake( 00, verifyRightView.width, verifyRightView.height);
    verifyRightView.contentMode = UIViewContentModeCenter;
    verifyField.rightViewMode = UITextFieldViewModeAlways;
    verifyField.rightView = verifyRightView;
    self.verifyRightView = verifyRightView;
    [verifyRightView addTarget:self action:@selector(verifyClick) forControlEvents:UIControlEventTouchUpInside];  // 点击获取验证码
    
    
//  创建登录按钮
    CGFloat loginBtnX = telFieldX;
    CGFloat loginBtnY = verifyFieldY + verifyFieldH +  35;
    CGFloat loginBtnW = telFieldW;
    CGFloat loginBtnH =  42;
    UIButton *loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(loginBtnX, loginBtnY, loginBtnW, loginBtnH)];
    [loginBtn setBackgroundImage:[UIImage imageWithName: @"  login "] forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageWithName: @" login_highlighted "] forState:UIControlStateHighlighted];
    [self.view addSubview:loginBtn];
    self.loginBtn = loginBtn;
    [loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];  //  点击获取验证码
    
    
// 创建一个导航栏
    UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake( 0, 0+statusBarHeight, self.view.frame.size.width,  44)];
    UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:nil];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle: @" 返回 "
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(clickLeftButton)];
    [navigationItem setTitle:NSLocalizedString( @" register ", nil)];
    [navigationBar pushNavigationItem:navigationItem animated:NO];
    [navigationItem setLeftBarButtonItem:leftButton];
    [self.view addSubview:navigationBar];
}

/* *
 *  创建TextFieldLeftView
 
*/
- ( void)creatTextFieldLeftViewWithTextfield:(UITextField *)textField andLeftViewImageName:(NSString *)name
{
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.keyboardType = UIKeyboardTypeNumberPad;
    [textField becomeFirstResponder];
    
     //  输入框左边图标
    UIImageView *leftView = [[UIImageView alloc] init];
    leftView.image = [UIImage imageWithName:name];
    leftView.width = leftView.image.size.width +  20;
    leftView.height = leftView.image.size.height;
    leftView.frame = CGRectMake( 1412, leftView.width, leftView.height);
    leftView.contentMode = UIViewContentModeCenter;
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.clearButtonMode = UITextFieldViewModeAlways;  //  清除按钮常显示
    textField.backgroundColor = [UIColor colorWithWhite: 1.0 alpha: 0.3];
    textField.font = [UIFont systemFontOfSize: 12];
    [self.view addSubview:textField];
}


#pragma mark - buttonClicks

/* *
 *   点击获取验证码
 
*/
- ( void)verifyClick
{
     //  如果手机号长度不为11位,提示号码不正确
     if (self.telField.text.length!= 11)
    {
         // 手机号码不正确
        UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" notice ", nil)
                                                      message:NSLocalizedString( @" errorphonenumber ", nil)
                                                      delegate:self
                                            cancelButtonTitle:NSLocalizedString( @" sure ", nil)
                                            otherButtonTitles:nil, nil];
        [alert show];
         return;
    }
    
     //  弹窗显示提示信息
    NSString* str=[NSString stringWithFormat: @" %@:%@ ",NSLocalizedString( @" willsendthecodeto ", nil),self.telField.text];
    QJLog( @" %@ ",self.telField.text);
    _str=[NSString stringWithFormat: @" %@ ",self.telField.text];
    UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" surephonenumber ", nil)
                                                  message:str  delegate:self
                                        cancelButtonTitle:NSLocalizedString( @" cancel ", nil)
                                        otherButtonTitles:NSLocalizedString( @" sure ", nil), nil];
    [alert show];
}

/* *
 *  弹出控制器
 
*/
- ( void)clickLeftButton
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/* *
 *  退出键盘
 
*/
- ( void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
{
    [self.view endEditing:YES];
}


#pragma mark - UIAlertDelegate
- ( void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
     if ( 1==buttonIndex)
    {
        [SMS_SDK getVerificationCodeBySMSWithPhone:self.telField.text zone: @" 86 " result:^(SMS_SDKError *error) {
             if (!error) {
#warning 这里填写验证码发送后的执行方法
                [self getVerify];
            } else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @" 错误 " message:[NSString stringWithFormat: @" 状态码:%zi ,错误描述:%@ ",error.errorCode,error.errorDescription]  delegate:self cancelButtonTitle: @" 确定 " otherButtonTitles:nil, nil];
                [alert show];
            }
        }];
    }
    
    
     if (alertView==_notGetSMSAlert)
    {
         if ( 1==buttonIndex)
        {
            QJLog( @" 重发验证码 ");
            [SMS_SDK getVerifyCodeByPhoneNumber:self.telField.text AndZone: @" 86 " result:^( enum SMS_GetVerifyCodeResponseState state)
             {
                  if ( 1==state)
                 {
                     QJLog( @" block 获取验证码成功 ");
                 }
                  else  if( 0==state)
                 {
                     QJLog( @" block 获取验证码失败 ");
                     NSString* str=[NSString stringWithFormat:NSLocalizedString( @" codesenderrormsg ", nil)];
                     UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" codesenderrtitle ", nil) message:str  delegate:self cancelButtonTitle:NSLocalizedString( @" sure ", nil) otherButtonTitles:nil, nil];
                     [alert show];
                 }
                  else  if (SMS_ResponseStateMaxVerifyCode==state)
                 {
                     NSString* str=[NSString stringWithFormat:NSLocalizedString( @" maxcodemsg ", nil)];
                     UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" maxcode ", nil) message:str  delegate:self cancelButtonTitle:NSLocalizedString( @" sure ", nil) otherButtonTitles:nil, nil];
                     [alert show];
                 }
                  else  if(SMS_ResponseStateGetVerifyCodeTooOften==state)
                 {
                     NSString* str=[NSString stringWithFormat:NSLocalizedString( @" codetoooftenmsg ", nil)];
                     UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" notice ", nil) message:str  delegate:self cancelButtonTitle:NSLocalizedString( @" sure ", nil) otherButtonTitles:nil, nil];
                     [alert show];
                 }

             }];
        }
    }

     if (alertView==_backButtonClickAlert) {
         if ( 0==buttonIndex)
        {
            [self dismissViewControllerAnimated:YES completion:^{
                [_updateTime invalidate];
                [_showRepeatButtonTimer invalidate];
            }];
        }
    }

}

/* *
 *  等待验证码
 
*/
- ( void)getVerify
{
    [_showRepeatButtonTimer invalidate];  //
    [_updateTime invalidate];
    
    count =  0;
     //  显示重新发送按钮
    NSTimer *showRepeatButtonTimer=[NSTimer scheduledTimerWithTimeInterval:timeCount
                                                                    target:self
                                                                  selector:@selector(showRepeatButton)
                                                                  userInfo:nil
                                                                   repeats:YES];
     //  倒计时label
    NSTimer *updateTime = [NSTimer scheduledTimerWithTimeInterval: 1
                                                           target:self
                                                         selector:@selector(updateTime)
                                                         userInfo:nil
                                                          repeats:YES];
    _showRepeatButtonTimer = showRepeatButtonTimer;
    _updateTime = updateTime;
}

/* *
 *  显示重新发送按钮
 
*/
-( void)showRepeatButton{
    [self.verifyRightView setTitle: @" 重新发送 " forState:UIControlStateNormal];

    [_showRepeatButtonTimer invalidate];
     return;
}

- ( void)leftButtonClick
{
    UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" notice ", nil)
                                                  message:NSLocalizedString( @" codedelaymsg ", nil)
                                                  delegate:self
                                        cancelButtonTitle:NSLocalizedString( @" back ", nil)
                                        otherButtonTitles:NSLocalizedString( @" wait ", nil), nil];
    _backButtonClickAlert=alert;
    [alert show];
}

/* *
 * 登录
 
*/
- ( void)login
{
     // 验证号码
    
// 验证成功后 获取通讯录 上传通讯录
    [self.view endEditing:YES];
    
     if(self.verifyField.text.length!= 4)
    {
        UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" notice ", nil)
                                                      message:NSLocalizedString( @" verifycodeformaterror ", nil)
                                                      delegate:self
                                            cancelButtonTitle: @" 确定 "
                                            otherButtonTitles:nil, nil];
        [alert show];
    }
     else
    {
        [SMS_SDK commitVerifyCode:self.verifyField.text result:^( enum SMS_ResponseState state) {
             if ( 1==state)
            {
                NSString* str=[NSString stringWithFormat:NSLocalizedString( @" verifycoderightmsg ", nil)];
                UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" verifycoderighttitle ", nil)
                                                              message:str
                                                              delegate:self
                                                    cancelButtonTitle:NSLocalizedString( @" sure ", nil)
                                                    otherButtonTitles:nil, nil];
                [alert show];
            }
             else  if( 0==state)
            {
                NSString* str=[NSString stringWithFormat:NSLocalizedString( @" verifycodeerrormsg ", nil)];
                UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" verifycodeerrortitle ", nil)
                                                              message:str
                                                              delegate:self
                                                    cancelButtonTitle:NSLocalizedString( @" sure ", nil)
                                                    otherButtonTitles:nil, nil];
                [alert show];
            }
        }];
    }
}

/* *
 *  没有收到验证码,重新发送验证码
 
*/
- ( void)CannotGetSMS
{
    NSString* str=[NSString stringWithFormat: @" %@:%@ ",NSLocalizedString( @" cannotgetsmsmsg ", nil) ,self.telField.text];
    UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString( @" surephonenumber ", nil) message:str  delegate:self cancelButtonTitle:NSLocalizedString( @" cancel ", nil) otherButtonTitles:NSLocalizedString( @" sure ", nil), nil];
    _notGetSMSAlert=alert;
    [alert show];
}

/* *
 *  更新时间label
 
*/
-( void)updateTime
{
    count++;
     if (count >= timeCount)
    {
        [_updateTime invalidate];
         return;
    }
    
    NSString *updateTimeStr =[NSString stringWithFormat: @" %@%i%@ ",NSLocalizedString( @" timelablemsg ", nil),timeCount-count,NSLocalizedString( @" second ", nil)];
    [self.verifyRightView setTitle:updateTimeStr forState:UIControlStateNormal];
}
@end

 

注意:

1.由于该代码中的所有控件布局都参照LOGO的位置和大小,所以,在使用该代码时,LOGO的大小将影响其他子控件的布局 

2.使用时将代码里的图片名称换掉自己的 

  

本文为原创,转载请注明本文连接 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM