[英]Making a countdown timer and run it in the background
I want to add a mute button to my app that when the user clicks it, he chooses a duration of the mute and while the mute is enabled the user won't get notifications from my app. 我想向我的应用程序添加一个静音按钮,当用户单击该按钮时,他选择静音的持续时间,并且在启用静音后,用户将不会从我的应用程序收到通知。
I thought NSTimer
is a good option, but how can I make a timer with it? 我以为NSTimer
是一个不错的选择,但是我该如何使用它呢? And how can I set that the timer
will run in the background aswell? 以及如何设置timer
也将在后台运行?
Note: I'm using location monitoring in the background. 注意:我在后台使用位置监控。
I don't think you need a running timer in the background - or any complicated solution: 我认为您不需要在后台运行计时器-或任何复杂的解决方案:
Use a timer when your app is in the foreground (as usual). 当您的应用程序位于前台时(通常)使用计时器。 Cancel the mute mode when it fires. 触发时取消静音模式。
When your app switches to the background mode and the timer is active, cancel the timer or let it running, depending on your needs. 当您的应用切换到后台模式并且计时器处于活动状态时,请根据需要取消计时器或使其运行。
Optionally, when your app is executing in background mode, just don't send notifications. (可选)当您的应用在后台模式下执行时,仅不发送通知。
If your app becomes suspended shortly after, your code wouldn't execute anyway. 如果您的应用不久之后被挂起,则您的代码将无法执行。
If your app still needs to obey the mute state when it switches to the foreground, calculate the duration of the date-time value which you stored when the mute mode has been activated and the current date-time and compare this with your timeout. 如果您的应用在切换到前台时仍需要遵循静音状态,请计算激活静音模式时存储的日期时间值的持续时间以及当前日期时间,并将其与超时进行比较。
NSTimer can fire a method after a certain time interval NSTimer可以在一定时间间隔后触发方法
First declare a NSTimer object, say "timer" 首先声明一个NSTimer对象,说“ timer”
self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(targetMethod:) userInfo:nil repeats:YES];
Now this timer will fire the targetMethod after every 1 sec. 现在,此计时器将每1秒触发一次targetMethod。 Time interval is 1 sec. 时间间隔是1秒。 Now define the target method 现在定义目标方法
- (void) targetMethod: (NSTimer*)theTimer
{
second++;
if(second==60)
{
minute++;
second=0;
}
}
I declared two int variable for minute and second count. 我为分钟和秒计数声明了两个int变量。 Now after every 1 sec the second will increase, and after every 60 sec, minute will increase. 现在,每隔1秒秒数将增加一次,而每隔60秒秒数将增加一分钟。 You can try it. 你可以试试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.