如何在按下Home按钮时保持Timer继续运行

问题描述:

我已经研究过如何在按下主页按钮时保持计时器运行。但我很困惑。

I have done research how to maintain the timer running when home button is pressed. But i am quite confused.

这是我的代码,我该如何修复它并且计时器继续在后台运行?提前致谢。

This is my code, how can i fix it and the timer continue running in background? Thanks in advance.

-(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

Marks the beginning of a new long-running background task. A unique identifier for the new background task. You must pass this value to the endBackgroundTask: method to mark the end of this task. This method returns UIBackgroundTaskInvalid if running in the background is not possible.

参数taskName
名称为在查看后台任务时显示在调试器中。如果为此参数指定nil,则此方法将根据调用函数或方法的名称生成名称。
handler
在应用程序的剩余后台时间达到0之前不久调用的处理程序。您应该使用此处理程序清理并标记后台任务的结束。未能明确结束任务将导致应用程序终止。在主线程上同步调用处理程序,在通知应用程序时暂时阻止应用程序暂停。

Parameter taskName The name to display in the debugger when viewing the background task. If you specify nil for this parameter, this method generates a name based on the name of the calling function or method. handler A handler to be called shortly before the app’s remaining background time reaches 0. You should use this handler to clean up and mark the end of the background task. Failure to end the task explicitly will result in the termination of the app. The handler is called synchronously on the main thread, blocking the app’s suspension momentarily while the app is notified.