为iPhone添加计时器
我正在尝试添加一个功能,在某些推送时,我的计时器将启动,即使应用程序关闭,计时器也将继续。假设我的分数是10,现在计时器启动了。一旦我关闭应用程序,也许下次如果我打开应用程序 1-如果在20分钟之前,它将显示倒计时运行 2-如果20分钟后再次启动应用程序,则会将点数增加到10 现在,什么样的计时器或类可以帮助我做到这一点为iPhone添加计时器,iphone,objective-c,cocoa-touch,Iphone,Objective C,Cocoa Touch,我正在尝试添加一个功能,在某些推送时,我的计时器将启动,即使应用程序关闭,计时器也将继续。假设我的分数是10,现在计时器启动了。一旦我关闭应用程序,也许下次如果我打开应用程序 1-如果在20分钟之前,它将显示倒计时运行 2-如果20分钟后再次启动应用程序,则会将点数增加到10 现在,什么样的计时器或类可以帮助我做到这一点 在应用程序终止的代理中,将时间保存在NSUserdefaults中,当您启动应用程序时,将其读回并继续添加时间。NSTimer将不会持续超过600秒,即使您的应用程序处于后台,
在应用程序终止的代理中,将时间保存在NSUserdefaults中,当您启动应用程序时,将其读回并继续添加时间。
NSTimer
将不会持续超过600秒,即使您的应用程序处于后台,其余时间将终止应用程序
您可以这样做:
NSString *prevTimestamp = [NSString stringWithFormat:@"%d",
[[NSDate date] timeIntervalSince1970]];
将此prevTimestamp
存储在NSUserDefaults
中,当返回应用程序时
NSString *nowTimestamp = [NSString stringWithFormat:@"%d",
[[NSDate date] timeIntervalSince1970]];
时间差将是
[nowTimestamp floatValue]-[prevTimestamp floatValue]
在您的ApplicationLegate中,您具有以下功能:
-(void)applicationDidEnterBackground:(UIApplication *)application;
及
通过这些函数,您可以通过以下方式跟踪时间:
-(void)applicationDidEnterBackground:(UIApplication *)application
{
backgroundTime = [[NSDate date] timeIntervalSince1970];
}
-(void)applicationWillEnterForeground:(UIApplication *)application
{
double timetoAppend = [[NSDate Date] timeIntervalSince1970] - backgroundTime];
// from here you need to add the timetoAppend to your own variable
}
关闭应用程序时,只需停止计时器……就像Mountain Lion说的那样:使用NSTimeInterval设置时间戳,并在重新进入应用程序时将其与新时间进行比较。
-(void)applicationDidEnterBackground:(UIApplication *)application
{
backgroundTime = [[NSDate date] timeIntervalSince1970];
}
-(void)applicationWillEnterForeground:(UIApplication *)application
{
double timetoAppend = [[NSDate Date] timeIntervalSince1970] - backgroundTime];
// from here you need to add the timetoAppend to your own variable
}