使用NSNotificationCenter计算应用程序在后台花费的时间

时间:2013-12-07 12:54:19

标签: ios objective-c nsnotificationcenter

我正在制作秒表,但是当应用程序进入后台时,它会停止计数。我已经尝试计算应用程序在后台花费的时间,然后使用NSNotificationCenter将该时间在几秒钟内发送到我的StopwatchViewController,我可以在其中添加已用时间。但是,它似乎不起作用:

在我的AppDelegate.m文件中:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSDate *currentDate= [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:currentDate forKey:@"backgroundDate"];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSDate *dateWhenAppGoesBg= (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"backgroundDate"];
NSTimeInterval timeSpentInBackground = [[NSDate date] timeIntervalSinceDate:dateWhenAppGoesBg];

NSNumber *n = [NSNumber numberWithDouble:timeSpentInBackground];

[[NSNotificationCenter defaultCenter] postNotificationName:@"NEWMESSAGE" object:n];

NSLog(@"%d", [n integerValue]);
}

在我的StopwatchViewController.m文件中:

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle { // Initialise view controller

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMessageReceived:) name:@"NEWMESSAGE" object:nil];

return self;
}

-(void)newMessageReceived:(NSNotification *) notification{
elapsedTime = [[notification object] intValue];

elapsedHours = elapsedTime / 3600;
elapsedTime = elapsedTime - (elapsedTime % 3600);

elapsedMinutes = elapsedTime / 60;
elapsedTime =  elapsedTime - (elapsedTime % 60);

elapsedSeconds = elapsedTime;

secondInt = secondInt + elapsedSeconds;
if (secondInt > 59) {
    ++minuteInt;
    secondInt -= 60;
}

minuteInt = minuteInt + elapsedMinutes;
if (minuteInt > 59) {
    ++hourInt;
    minuteInt -= 60;
}

hourInt = hourInt + elapsedHours;
if (hourInt > 23) {
    hourInt = 0;
}
}

1 个答案:

答案 0 :(得分:4)

如果我没有完全忽视这一点,我认为你是以错误的方式攻击这个问题。

如果您正在制作秒表,那么只有两个有趣的时间点是您启动秒表时的点和当前时间。没有理由计算您的应用在后台时所经过的时间。

相反,只需存储秒表启动的时间点,然后添加例如a NSTimer通过将此时间与当前时间(即[NSDate date)进行比较来更新计时器显示。然后,您不必担心当您的应用进入后台模式时会发生什么。

编辑一些想法(免责声明:无法访问Xcode,所以我只是从头脑中输入):

当用户启动计时器时,保存当前时间并开始NSTimer

- (void) didTapStart:(id)sender {
   self->startTime = [NSDate date];
   [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerElapsed:) userInfo:nil repeats:YES];
}

然后更新计时器事件

上的显示
- (void) timerElapsed:(id)sender {
   NSDateInterval elapsed = [[NSDate date] timeIntervalSinceDate:self->startTime];
   int hours = (int)elapsed / 3600;
   int minutes = ((int)elapsed / 60) % 60;
   int seconds = (int)elapsed % 60;
   NSString* elapsedString = [NSString stringWithFormat:@"Elapsed: %d:%02d:%02d",hours,minutes,seconds];
}
相关问题