如何在应用程序的后台运行计时器? [英] How to run the timer in background of the application?

查看:108
本文介绍了如何在应用程序的后台运行计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想减少时间倒计时。因此,如果用户最小化应用,则应用加载背景。如何在应用程序后台运行计时器?我使用以下代码。当app最小化时,计时器停止。请帮帮我。

I want to reduce the count down of the time. So If the user minimize app then app loading the background. How can run the timer in application background? I am using the below code. When app is minimized timer is stopped. Please help me.

        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerCountDown) userInfo:nil repeats:YES];

- (void)timerCountDown
{
    if(secondsLeft > 0 ) {
        secondsLeft -- ;
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
    }
}


推荐答案

我得到了答案,它完美地工作。

I got the answer, its working perfectly.

UIBackgroundTaskIdentifier bgTask =0;
UIApplication  *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
}];

timer = [NSTimer
               scheduledTimerWithTimeInterval:1.0
               target:self
               selector:@selector(timerCountDown:)
               userInfo:nil
               repeats:YES];

这篇关于如何在应用程序的后台运行计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆