当app进入后台时如何继续运行NSTimer [英] how to keep running NSTimer when app goes in background

查看:99
本文介绍了当app进入后台时如何继续运行NSTimer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建益智游戏应用程序,并且我正在使用NSTimer显示时间(即01:20)。当应用程序在后台运行时NSTimer暂停但我想继续它甚至应用程序处于后台状态。

I am creating puzzle game application and in that I am displaying time (i.e 01:20) using NSTimer. NSTimer is paused when application gone in background but i want to continue it even application is in background state.

例如当应用程序进入时,计时器计数为15秒背景,我放置5秒并变为前景现在我需要将计时器计数更改为20秒

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

我搜索了很多,但没有得到很好的答案。
所以请建议我如何实现这一目标。

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.

要记录开始时间,请将其写入文件,如下所示,可能在appWillResignActive:

To record the start time, write it to a file as follows, probably in 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

当appWillBecomeActive:

When 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

此时的经过时间是:

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

所有上述内容均可在不在后台运行的情况下完成。如果您确实需要在后台触发计时器,请参阅苹果参考。在后台执行下。简而言之,您可以这样做,但Apple会在批准应用程序之前让您满足几个标准 - 例如它必须是有限的并为用户提供实用程序。

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

这篇关于当app进入后台时如何继续运行NSTimer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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