计算应用程序确实进入应用程序之前的秒数持续时间确实输入前景

时间:2014-09-29 08:05:52

标签: ios objective-c ipad nstimer

我开始认识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];

       }

}

2 个答案:

答案 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)

  • 根据Apple开发者指南,您无法在背景上进行UI更新" 您可以存储任何变量或对象的值,当它出现在mainThread上时,您可以更新您的标签