简体   繁体   English

应用程序在后台运行时如何保持运行NSTimer

[英]how to keep running NSTimer when app goes in background

I am creating puzzle game application and in that I am displaying time (ie 01:20) using NSTimer. 我正在创建益智游戏应用程序,并且正在使用NSTimer显示时间(即01:20)。 NSTimer is paused when application gone in background but i want to continue it even application is in background state. 当应用程序进入后台时,NSTimer被暂停,但是即使应用程序处于后台状态,我也要继续。

for example timer count is 15 sec when app gone in background and I put it for 5 sec and become in foreground now I need to timer count changes to 20 sec 例如, 当应用程序进入后台时,计时器计数为15秒 ,我将其放置5秒钟,然后进入前台,现在我需要将计时器计数更改为20秒

I have searched a lot but didn't get good answer. 我搜索了很多,但没有得到很好的答案。 So Please suggest me how can I achieve this. 因此,请建议我如何实现这一目标。

Don't think of a timer as an object for timing something. 不要将计时器视为用于计时的对象。 Think of it rather as an object that pulses at a given frequency. 可以将其视为以给定频率脉动的对象。 To measure time, record a start time and compare it to the current time. 要测量时间,请记录开始时间并将其与当前时间进行比较。

To record the start time, write it to a file as follows, probably in appWillResignActive: 要记录开始时间,请按照以下步骤将其写入文件,可能在appWillResignActive中:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *filename = [path stringByAppendingPathComponent:@"saveme.dat"];

NSData * data = [NSKeyedArchiver archivedDataWithRootObject:self.startDate];
[data writeToFile:filename atomically:NO];
// invalidate timer

When appWillBecomeActive: 当appWillBecomeActive时:

NSData *data = [NSData dataWithContentsOfFile:filename];    // using the same code as before
self.startDate = [NSKeyedUnarchiver unarchiveObjectWithData:data];
// start a timer for the purpose of pulsing only

Elapsed time at this point is: 此时的经过时间为:

NSDate *now = [NSDate date];
NSTimeInterval = [now timeIntervalSinceDate:self.startDate];

All of the foregoing can be done without running in the background. 无需在后台运行即可完成所有上述操作。 If you really need a timer to fire in the background, see this apple ref . 如果您确实需要在后台触发计时器,请参阅此Apple参考 Under "Background Execution". 在“背景执行”下。 In a nutshell, you can do it, but Apple will make you meet several criteria before approving the app -- like it must be finite and provide utility for the user. 简而言之,您可以执行此操作,但是Apple会在批准该应用程序之前使您满足多个条件-就像它必须是有限的并为用户提供实用程序。

You're going to need to write that information out to a file or cache the time at exit. 您将需要将该信息写到文件中或在退出时缓存时间。 Then when the application resumes you read that value in, do some math, and restart your timer. 然后,当应用程序恢复运行时,您读入该值,进行一些数学运算,然后重新启动计时器。

In your AppDelegate as the app is going to background save the time to a file or NSUserDefaults. 在应用程序进入后台时,在您的AppDelegate中将时间保存到文件或NSUserDefaults中。 You can call NSDate's class method to get an Integer value you can easily store. 您可以调用NSDate的class方法来获取可以轻松存储的Integer值。

+ (NSTimeInterval)timeIntervalSinceReferenceDate

At application resume, read in the value. 在应用程序恢复时,读入该值。 Get the current timeIntervalSinceReferenceDate and subtract. 获取当前的timeIntervalSinceReferenceDate并减去。 You should have the number of seconds that have elapsed. 您应该具有已过去的秒数。

Create a NSDate ivar in your class to manage the starting time. 在您的班级中创建一个NSDate ivar来管理开始时间。

@implementation SomeClass {
  NSDate *startTime;
}

For your timer, simply calculate the time through math on this date. 对于您的计时器,只需通过数学计算该日期的时间即可。 Your timer is more used to invoke the method that does this calculation rather than determine the time itself... 您的计时器更多地用于调用执行此计算的方法,而不是确定时间本身。

[NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

Logic for your method... 方法的逻辑...

- (void)updateTimer {
  if (!startTime) {
    startTime = [NSDate date];
  }
  NSInteger secondsSinceStart = -(NSInteger)[startTime timeIntervalSinceNow];
  NSLog(@"%d", secondsSinceStart);
}

I would recommend saving the start time as an NSDate object, and then having an NSTimer that, every second while the app is running, updates the displayed time by calculating the time interval between the current time and the start time. 我建议将开始时间保存为NSDate对象,然后让NSTimer在应用程序运行时每秒通过计算当前时间和开始时间之间的时间间隔来更新显示的时间。 Pause the timer when your app goes into the background (so that you don't get a lot of unnecessary fires when your app starts back up) and restart it whenever the app enters the foreground. 当应用程序进入后台时暂停计时器(这样一来,当应用程序启动后,您就不会遇到很多不必要的火灾),并在应用程序进入前台时重新启动它。

If you want the data to be preserved across the app shutting completely (by being left in the background for too long, or closed in the app switcher) then you'll need to save data to disk at appropriate times. 如果要在整个应用程序关闭时(通过在后台放置太长时间或在应用程序切换器中将其关闭)保存数据,则需要在适当的时间将数据保存到磁盘。

self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5f
                                 target:self
                               selector:@selector(showTime)
                               userInfo:NULL
                                repeats:YES];

- (void)showTime
{
NSDate *now=[NSDate date];
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"HH:mm:ss"];
timeLabel.text=[dateFormatter stringFromDate:now];
}

Hope this answer will help you.... 希望这个答案对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使应用程序在ios中进入后台,也可以保持NSTimer运行 - Keep NSTimer running even application goes in background in ios 当应用程序在后台时调度 NSTimer? - Scheduled NSTimer when app is in background? 如何在iOS 7的后台保持NSTimer活着? - How to keep NSTimer alive in Background on iOS 7? 当应用程序进入后台时如何运行NSThread - how to run NSThread when app goes to background 当应用程序进入后台时,如何创建“返回应用程序”状态栏? - How to create a “return to app” status bar when app goes to the background? 在多任务iPhone应用程序的后台运行NSTimer以打开/关闭定位服务 - running an NSTimer in the background of a multitasking iPhone app to turn location service on/off 如果当 iOS 应用程序在后台时 NSTimer 不起作用,我怎样才能让我的应用程序定期唤醒? - If NSTimer does not work when an iOS app is in the background, how can I get my app to wake up periodically? 应用程序进入后台时如何取消Everyplay SDK录制? - How to cancel Everyplay SDK recording when app goes to background? 当应用程序进入后台状态时如何取消AVExportSession? - How to Cancel AVExportSession when app goes to background state? 应用程序进入后台或手机锁定时如何获取位置? - How to get location when app goes to background or phone is locked?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM