iOS开发-关于短信验证码倒计时

本文介绍了一种iOS应用中实现倒计时功能的方法,即使应用切换到后台也能保持倒计时继续运行。通过记录应用程序进入后台和返回前台的时间戳来调整剩余倒计时时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我们获取短信验证码后,通常情况下,我们会写一个多少秒后重新获取,此时,如果我们不做任何处理,当程序进入后台(按“HOME”键),倒计时也会停止,当重新返回前台时,倒计时还是从原来进入后台的时间继续倒计时。

因此,我们需要在程序进入后台时,倒计时依旧可以进行,首先项目中要获取到时间戳里的毫秒单位:

/************************↓↓↓↓**DEMO**↓↓↓↓**************************/

主要代码:

-(void)dealloc

{

    [selfremoveObserver];

    [superdealloc];

}

//移除通知

-(void)removeObserver

{

    [[NSNotificationCenterdefaultCenter]removeObserver:self];

}


-(id)initWithCoder:(NSCoder *)aDecoder

{

    self = [superinitWithCoder:aDecoder];

    if (self) {

        [selfaddObserver];

    }

    returnself;

}

//监听通知

-(void)addObserver

{

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleAppDidBackGround)name:UIApplicationDidEnterBackgroundNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleAppDidEnterForeground)name:UIApplicationWillEnterForegroundNotificationobject:nil];

}

//程序进入后台

-(void)handleAppDidBackGround

{

    _backGroundInterval = (longlongint)[[NSDatedate]timeIntervalSince1970];//取当前时间戳

}

//程序进入前台

-(void)handleAppDidEnterForeground

{

    longlongint foreInterval = (longlongint)[[NSDatedate]timeIntervalSince1970];//取当前时间戳

    

    int differ = (int)( foreInterval  -_backGroundInterval);

    

    _timerNumber = (_timerNumber >=0)?(_timerNumber - differ):_timerNumber;

}

/************************↑↑↑↑**DEMO**↑↑↑↑***********************/


/*****************************时间戳相关资料*************************************/


获取到当前时间戳方法:

NSTimeInterval time = [[NSDate date] timeIntervalSince1970];

long long int date = (long long int)time;
NSLog(@”date\n%d”, date); //1295322949

?
首先 [[NSDate date] timeIntervalSince1970] 是可以获取到后面的毫秒 微秒的 ,只是在保存的时候省略掉了, 如一个时间戳不省略的情况下为 1395399556.862046 ,省略掉后为一般所见 1395399556 。所以想取得毫秒时用获取到的时间戳 *1000 ,想取得微秒时 用取到的时间戳 * 1000 * 1000 。       

 可转换为字符型:

    NSString *timeString = [NSString stringWithFormat:@"%f", a];//转为字符型


如果你想格式化输出 可以:

 

   NSDateFormatter *formatter = [[NSDateFormatter allocinit];

// 设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

   [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];

   NSString *date = [formatter stringFromDate:[NSDate date]];

    NSString *timeLocal = [[NSString allocinitWithFormat:@"%@",date];

    NSLog(@"%@",timeLocal);


参考文章:

 

ios NSDate 时间戳 时间间隔

iOS标准时间与时间戳相互转换

iOS标准时间与时间戳相互转换





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值