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

前言

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

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

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

<pre>

  • (void)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(timer);
    //主线程设置按钮样式
    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(timer);
    }
    </pre>

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

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

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

import "AppDelegate.h"

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

@end

@implementation AppDelegate

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

    count=0;
    return YES;
    }

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

  • (void)applicationWillEnterForeground:(UIApplication *)application {
    NSLog(@"进入前台");
    [self endBack];
    }

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

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

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

@end
</pre>

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

3、 扩充无限倒计时

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

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

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

配置信息.png

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

import "AppDelegate.h"

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

@end

@implementation AppDelegate

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

    count=0;
    return YES;
    }

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

  • (void)applicationWillEnterForeground:(UIApplication *)application {
    NSLog(@"进入前台");
    [self endBack];
    }

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

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

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

}

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

@end
</pre>

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

import "ViewController.h"

import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@property(strong, nonatomic)AVAudioPlayer *mPlayer;

@property(assign, nonatomic)CGFloat mCount;

@end

@implementation ViewController

  • (void)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];
    }

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

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

}

-(void)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>

完。

自助者,天助之。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,657评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,889评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,057评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,509评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,562评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,443评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,251评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,129评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,561评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,779评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,902评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,621评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,220评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,838评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,971评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,025评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,843评论 2 354

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,116评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,656评论 18 139
  • IOS开发之----详解在IOS后台执行 文一 我从苹果文档中得知,一般的应用在进入后台的时候可以获取一定时间来...
    dongfang阅读 1,383评论 0 7
  • 自从古老的iOS4以来,当用户点击home建的时候,你可以使你的APP们在内存中处于suspended(挂起)状态...
    木易林1阅读 3,130评论 1 4
  • 有许多想做的事情,包括已经在做的了和存留在想法中的,例如跳拉丁、例如写公众号、例如在豆瓣发布活动、例如去找认为有趣...
    黑眼圈圈阅读 192评论 0 0