问题
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? And how can I set that the timer
will run in the background aswell?
Note: I'm using location monitoring in the background.
回答1:
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.
回答2:
NSTimer can fire a method after a certain time interval
First declare a NSTimer object, say "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. Time interval is 1 sec. 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. Now after every 1 sec the second will increase, and after every 60 sec, minute will increase. You can try it.
来源:https://stackoverflow.com/questions/35286466/making-a-countdown-timer-and-run-it-in-the-background