【问题标题】:How to maintain Timer to continue running when Home button is pressed按下 Home 键时如何保持 Timer 继续运行
【发布时间】:2026-01-15 21:50:02
【问题描述】:

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

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

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

【问题讨论】:

  • 如果应用程序在后台,您是否希望在计时器结束时发生任何事情?或者如果应用程序再次被带到前面,您是否希望计时器像以前一样继续(减去它在后台的任何时间)?
  • 我希望计时器在应用程序处于后台时继续计时。提前致谢。
  • 为什么需要定时器在后台运行?您的应用将无法运行。
  • 当您的应用程序进入后台时,节省时间。当它在前台恢复时,获取当前时间。从当前时间中减去保存的后台时间,您就会知道您的计时器已经运行了多长时间。
  • 不是“可能一个好主意”。这是正确的解决方案。您的应用程序可能会在后台被杀死。当用户尝试返回应用程序时,您需要处理该应用程序被杀死并重新启动。

标签: ios objective-c


【解决方案1】:
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

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

【讨论】:

    最近更新 更多