我开始认识NSTimer不会在后台工作。我的应用程序要求我即使在后台运行计时器。我决定做的是从App
计算秒持续时间- (void)applicationDidEnterBackground:(UIApplication *)application
致
- (void)applicationWillEnterForeground:(UIApplication *)application
并减去 SecondsLeft 变量中的秒数...如何执行此操作。 ?
viewControll.h
@property(strong,nonatomic)NSTimer *timer;
viewController.m
int secondsLeft = 1800;
- (void)handleLongPress:(UILongPressGestureRecognizer*)gestureRecognizer
{
if (gestureRecognizer.state == UIGestureRecognizerStateEnded)
{
if (isLongPressed)
{
isLongPressed= FALSE;
}
else
{
isLongPressed= TRUE;
secondsLeft = minutes = seconds = 0;
if (timerr) {
[timerr invalidate];
}
timerr = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
secondsLeft=1800;
}
}
//Updates counter
- (void)updateCounter:(NSTimer *)theTimer
{
if(secondsLeft > 0 )
{
secondsLeft -- ;
//hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
NSLog(@"the timer %@ ",[NSString stringWithFormat:@"%02d:%02d", minutes, seconds] );
}
else if (secondsLeft ==0)
{
[timerr invalidate];
}
}
答案 0 :(得分:2)
输入背景时执行:
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSDate date] forKey:@"TimeEnterBackground"];
[defaults synchronize];
再次进入前景后:
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSDate* enteringBackground = [defaults objectForKey:@"TimeEnterBackground"];
NSInteger timeInBackground = [[NSDate date] timeIntervalSince1970] - [enteringBackground timeIntervalSince1970];
即使应用程序在后台运行时关闭
,这也会有效答案 1 :(得分:2)