网络编程

当前位置:永利402游戏网站-永利402com官方网站 > 网络编程 > 在后台推行短信验证码倒计时

在后台推行短信验证码倒计时

来源:http://www.xtcsyb.com 作者:永利402游戏网站-永利402com官方网站 时间:2019-09-11 14:45
前言

我们一般做的短信验证码功能,应用在前台运行的时候,肯定是没有问题的,但是点击一下Home键进入后台挂起的状态,我们的定时器就停止了。

网上很多说记录什么进入后台的时间,我觉的那太费事了,我们完全可以通过申请应用在后台执行来执行我们的倒计时。

一、AppDelegate.m里面引入类ViewController.h然后设置首页面

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        ViewController *mainVC=[[ViewController alloc]init];

         UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:mainVC];

         self.window.rootViewController = nav;

         [self.window makeKeyAndVisible];

        return YES;

}

1、先放我们倒计时的代码,这段代码在模拟器运行是没有问题的,但是在真机进入挂起状态会停止

<pre>

  • sentPhoneCodeTimeMethod {//倒计时时间 - 60S__block NSInteger timeOut = 59;//执行队列dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//计时器 -》 dispatch_source_set_timer自动生成dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);

    dispatch_source_set_event_handler(timer, ^{if (timeOut <= 0) {dispatch_source_cancel;//主线程设置按钮样式dispatch_async(dispatch_get_main_queue(), ^{// 倒计时结束[self.captchaButton setBackgroundImage:kImage(kCaptchaButtonNormal) forState:UIControlStateNormal];[self.captchaButton setTitle:kCaptchaButtonTitle forState:UIControlStateNormal];[self.captchaButton setEnabled:YES];

     [self.captchaButton setUserInteractionEnabled:YES]; }); } else { //开始计时 //剩余秒数 seconds NSInteger seconds = timeOut % 60; NSString *strTime = [NSString stringWithFormat:@"%.1ld", seconds]; //主线程设置按钮样式 dispatch_async(dispatch_get_main_queue(), ^{ [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1.0]; [self.captchaButton setBackgroundImage:kImage(kCaptchaButtonSelected) forState:UIControlStateNormal]; NSString *title = [NSString stringWithFormat:@"%@ s",strTime]; [self.captchaButton setTitle:title forState:UIControlStateNormal]; [UIView commitAnimations]; //计时器件不允许点击 [self.captchaButton setUserInteractionEnabled:NO]; }); timeOut--; }
    

    });dispatch_resume;}</pre>

二、新建FlashPageView类继承UIView,用来设置启动页

1、FlashPageView.h

#define kscreenWidth [UIScreen mainScreen].bounds.size.width

#define kscreenHeight [UIScreen mainScreen].bounds.size.height

#import  <UIKit/UIKit.h>

typedef void (^PushToAdBlock)(void);

@interface FlashPageView : UIView

@property (nonatomic, strong) UIImageView *adView;/** 图片*/

@property (nonatomic, copy) NSString *filePath;/** 图片路径*/

@property (nonatomic,copy) PushToAdBlock  pushToAdBlock;

- (void)show;/** 显示启动页面方法*/

-(void) TouchPushToAdBlock:(PushToAdBlock)pushToAdBlock;

@end

2、FlashPageView.m

#import "FlashPageView.h"

@interface FlashPageView ()

@property (nonatomic, strong) UIButton *countBtn;  /**倒计时按钮*/

@property (nonatomic, strong) NSTimer *countTimer; /**定时器*/

@property (nonatomic, assign) int count;  /**倒计时*/

@end

static int const showtime = 10;  // 启动页显示的时间

@implementation FlashPageView

- (instancetype)initWithFrame:(CGRect)frame{

        if (self = [super initWithFrame:frame]) {

        // 1.闪频页图片

        _adView = [[UIImageView alloc] initWithFrame:frame];

       _adView.image = [UIImage imageNamed:@"启动页"];

       _adView.userInteractionEnabled = YES;//用户交互

       _adView.contentMode = UIViewContentModeScaleAspectFill;// 等比例缩放至父容器完全装下图片为止.图片没有变形

        _adView.clipsToBounds = YES;

         UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushToAd)];  //利用手势给控件添加点击事件

        [_adView addGestureRecognizer:tap];

        // 2.跳过按钮

        CGFloat btnW = 60;

        CGFloat btnH = 30;

        _countBtn = [[UIButton alloc] initWithFrame:CGRectMake(kscreenWidth - btnW - 24, btnH, btnW, btnH)];

        [_countBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];

        [_countBtn setTitle:[NSString stringWithFormat:@"跳过%d", showtime] forState:UIControlStateNormal];

        _countBtn.titleLabel.font = [UIFont systemFontOfSize:15];

        [_countBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

        _countBtn.backgroundColor = [UIColor colorWithRed:38 /255.0 green:38 /255.0 blue:38 /255.0 alpha:0.6];

         _countBtn.layer.cornerRadius = 4;

         [_countBtn addTarget:self action:@selector(countBtnClick) forControlEvents:UIControlEventTouchUpInside];

         [self addSubview:_adView];

         [self addSubview:_countBtn];

        }

        return self;

}

- (NSTimer *)countTimer{

          if (!_countTimer) {

                   _countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];

         }

         return _countTimer;

}

-(void)countBtnClick{

         [self dismiss];

}

- (void)setFilePath:(NSString *)filePath{

        _filePath = filePath;

       _adView.image = [UIImage imageWithContentsOfFile:filePath];

}

- (void)pushToAd{

       NSLog(@"点击图片");

        __weak typeof(self) WeakSelf = self;

       if (WeakSelf.pushToAdBlock) {

               WeakSelf.pushToAdBlock();

        }

         [self dismiss];

}

-(void) TouchPushToAdBlock:(PushToAdBlock)pushToAdBlock{

         self.pushToAdBlock = pushToAdBlock;

}

- (void)countDown{

         _count --;

         [_countBtn setTitle:[NSString stringWithFormat:@"跳过%d",_count] forState:UIControlStateNormal];

        if (_count == 0) {

                [self.countTimer invalidate];

                self.countTimer = nil;

                [self dismiss];

          }

}

- (void)show{

            // 倒计时方法1:GCD

            //    [self startCoundown];

            // 倒计时方法2:定时器

              [self startTimer];

              UIWindow *window = [UIApplication sharedApplication].keyWindow;

             [window addSubview:self];

}

// 定时器倒计时

- (void)startTimer{

           _count = showtime;

           [[NSRunLoop mainRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];//定时器只运行在NSDefaultRunLoopMode下,一旦RunLoop进入其他模式,这个定时器就不会工作,该模式表示在没有输入源的情况下

}

//// GCD多线程倒计时

//- (void)startCoundown{

//    __block int timeout = showtime + 1; //倒计时时间 + 1

//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

//    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

//    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒执行

//    dispatch_source_set_event_handler(_timer, ^{

//    if(timeout <= 0){ //倒计时结束,关闭

//            dispatch_source_cancel(_timer);

//            dispatch_async(dispatch_get_main_queue(), ^{

//                [self dismiss];

//            });

//        }else{

//            dispatch_async(dispatch_get_main_queue(), ^{

//              [_countBtn setTitle:[NSString stringWithFormat:@"跳过%d",timeout] forState:UIControlStateNormal];

//            });

//            timeout--;

//        }

//    });

//    dispatch_resume(_timer);

//}

// 移除闪频页面

- (void)dismiss{

            [UIImageView animateWithDuration:2.0 animations:^{

                     self.adView.alpha = 0;

                     [_countBtn removeFromSuperview];

                     [self.adView removeFromSuperview];

            } completion:^(BOOL finished) {

                    [self removeFromSuperview];

            }];

}

2、下面是我们用到的一个小技巧

一般来说,如果不进行后台申请,在iOS系统上,当应用退到后台后,只有5s的时间去执行代码,之后将进入挂起状态。只有像音频播放、定位、newsstand、VoIP等功能才能持续在后台运行。但是开发其它应用是我们可以通过申请后台,来获得3分钟的后台执行代码时间(iOS7以前是10分钟)。

所以我们决定申请3分钟来执行我们1分钟的倒计时代码:<pre>

@interface AppDelegate (){NSInteger count;}@property(strong, nonatomic)NSTimer *mTimer;@property(assign, nonatomic)UIBackgroundTaskIdentifier backIden;

@end

@implementation AppDelegate

  • application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {// Override point for customization after application launch.

    count=0;return YES;}

  • applicationDidEnterBackground:(UIApplication *)application {_mTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countAction) userInfo:nil repeats:YES];[[NSRunLoop currentRunLoop] addTimer:_mTimer forMode:NSRunLoopCommonModes];[self beginTask];}

  • applicationWillEnterForeground:(UIApplication *)application {NSLog;[self endBack];}

//计时-countAction{NSLog(@"%li",count++);}

//申请后台-beginTask{NSLog(@"begin=============");_backIden = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{//在时间到之前会进入这个block,一般是iOS7及以上是3分钟。按照规范,在这里要手动结束后台,你不写也是会结束的NSLog(@"将要挂起=============");[self endBack];}];}

//注销后台-endBack{NSLog(@"end=============");[[UIApplication sharedApplication] endBackgroundTask:_backIden];_backIden = UIBackgroundTaskInvalid;}

@end</pre>

这样就轻松、完美解决了我们的需求了!!!

三、在ViewController.m里面引入类FlashPageView.h然后调用方法

- (void)viewDidLoad {

            [super viewDidLoad];

            self.view.backgroundColor = [UIColor whiteColor];

            self.title = @"首页";

            FlashPageView *flashPage = [[FlashPageView alloc]initWithFrame:self.view.bounds];

            [flashPage show];

}

3、 扩充无限倒计时

慎用!因为这个需要申请后台播放音频的权限。如果你的应用不是相关应用,AppStore审核可能不会通过。

先在我们的info.plist文件配置中,添加一行,如下两个属性:

Required background modes``App plays audio or streams audio/video using AirPlay

图片 1配置信息.png

AppDelegate.m文件中代码还是和上面一样,设置 UIBackgroundTaskIdentifier<pre>

@interface AppDelegate (){NSInteger count;}@property(strong, nonatomic)NSTimer *mTimer;@property(assign, nonatomic)UIBackgroundTaskIdentifier backIden;

@end

@implementation AppDelegate

  • application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {// Override point for customization after application launch.

    count=0;return YES;}

  • applicationDidEnterBackground:(UIApplication *)application {_mTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countAction) userInfo:nil repeats:YES];[[NSRunLoop currentRunLoop] addTimer:_mTimer forMode:NSRunLoopCommonModes];[self beginTask];}

  • applicationWillEnterForeground:(UIApplication *)application {NSLog;[self endBack];}

//计时-countAction{NSLog(@"%li",count++);}

//申请后台-beginTask{NSLog(@"begin=============");_backIden = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

 NSLog(@"将要挂起============="); [self endBack];}];

}

//注销后台-endBack{NSLog(@"end=============");[[UIApplication sharedApplication] endBackgroundTask:_backIden];_backIden = UIBackgroundTaskInvalid;}

@end</pre>

在我们需要后台运行的控制器中,例如ViewController.m<pre>

@interface ViewController ()

@property(strong, nonatomic)AVAudioPlayer *mPlayer;

@property(assign, nonatomic)CGFloat mCount;

@end

@implementation ViewController

  • viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.

    _mCount = 0;

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(countTime) userInfo:nil repeats:YES];[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];}

-countTime{_mCount+=10;NSLog(@"%f",_mCount);

if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 60.) {//当剩余时间小于60时,开如播放音乐,并用这个假前台状态再次申请后台 NSLog(@"播放%@",[NSThread currentThread]); [self playMusic]; //申请后台 [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ NSLog; }];}

}

-playMusic{//1.音频文件的url路径,实际开发中,用无声音乐NSURL *url=[[NSBundle mainBundle]URLForResource:@"欢沁.mp3" withExtension:Nil];

//2.创建播放器(注意:一个AVAudioPlayer只能播放一个url)_mPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:Nil];//3.缓冲[_mPlayer prepareToPlay];//4.播放[_mPlayer play];

}

@end</pre>

完。

自助者,天助之。

本文由永利402游戏网站-永利402com官方网站发布于网络编程,转载请注明出处:在后台推行短信验证码倒计时

关键词: