我已经研究了如何在按下主页按钮时保持计时器运行。但我很困惑。
这是我的代码,如何修复它并且计时器继续在后台运行?提前谢谢。
-(id)init {
if (self = [super init]) {
self.timer = [[NSTimer alloc] init];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startTimer) userInfo:nil repeats:YES];
}
return self;
}
+(Timer *)sharedSingleton {
static Timer *sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedSingleton = [[Timer alloc] init];
});
return sharedSingleton;
}
-(void)startTimer {
i++;
_count = [NSNumber numberWithInteger:i];
[[NSNotificationCenter defaultCenter] postNotificationName:COUNT object:_count];
}
答案 0 :(得分:3)
NSTimer *timer;
- (void)viewDidLoad {
[super viewDidLoad];
UIBackgroundTaskIdentifier backgroundTaskIdentifire =0;
UIApplication *application = [UIApplication sharedApplication];
backgroundTaskIdentifire = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:backgroundTaskIdentifire];
}];
timer = [NSTimer
scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(yourFunction)
userInfo:nil
repeats:YES];
}
-(void)yourFunction{
NSLog(@"Timer");
}
标记新的长时间运行后台任务的开始。
新后台任务的唯一标识符。您必须将此值传递给endBackgroundTask:方法以标记此任务的结束。如果无法在后台运行,此方法将返回UIBackgroundTaskInvalid
。
参数taskName 查看后台任务时在调试器中显示的名称。如果为此参数指定nil,则此方法将根据调用函数或方法的名称生成名称。 处理器 在应用程序的剩余后台时间到达之前不久调用的处理程序。您应该使用此处理程序来清理并标记后台任务的结束。未能明确结束任务将导致应用程序终止。处理程序在主线程上同步调用,在通知应用程序时暂时阻止应用程序的暂停。
答案 1 :(得分:1)
1)。声明这个变量。
UIBackgroundTaskIdentifier counterTask;
2).Add - (void)startTimer
counterTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// If you're worried about exceeding 10 minutes handle it here
}];
3)。添加 - (void)stoptimer
[[UIApplication sharedApplication] endBackgroundTask:counterTask];
在后台运行计时器。