如何保持定时器在按下主屏幕button时继续运行

我已经做了研究如何保持定时器运行时,主页button被按下。 但是我很困惑。

这是我的代码,我如何解决这个问题,定时器继续在后台运行? 提前致谢。

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

 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查看后台任务时显示在debugging器中的名称。 如果为此参数指定nil,则此方法将根据调用函数或方法的名称生成一个名称。 处理程序将在应用程序的剩余后台时间到达之前立即调用的处理程序。您应该使用此处理程序来清理并标记后台任务的结束。 未能明确结束任务将导致应用程序终止。 处理程序在主线程中同步调用,在应用程序被通知时暂时阻止应用程序的暂停。

1)。 声明这个variables。

 UIBackgroundTaskIdentifier counterTask; 

2).Add – (void)startTimer

 counterTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ // If you're worried about exceeding 10 minutes handle it here }]; 

3)。 从 – (void)停止添加

  [[UIApplication sharedApplication] endBackgroundTask:counterTask]; 

在后台运行计时器。