2

正如标题所说:如何确定我的 iOS App 已关闭或在后台运行了多长时间?我需要知道这一点,因为如果应用程序已关闭或已在后台运行超过 3 小时,我想调用一个方法。

4

2 回答 2

3

您可以通过在 NSUserDefaults 中保存时间来跟踪应用程序被后台/终止的时间,然后在重新启动应用程序后使用它们。试试这个代码(我已经格式化了日期,因为我在我的应用程序中以格式化的方式进一步使用它们。您可以选择忽略日期格式。):

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
    NSString *backGroundTime = [dateFormat stringFromDate:[NSDate date]];
    [[NSUserDefaults standardUserDefaults]setValue:backGroundTime forKey:@"backGroundTime"];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
    NSString *foreGroundTime = [dateFormat stringFromDate:[NSDate date]];
    NSString *backGroundTime = [[NSUserDefaults standardUserDefaults]valueForKey:@"backGroundTime"];
    [self minCalculation_backgroundtime:backGroundTime forgroundTime:foreGroundTime];
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

// Call this method to calculate the duration of inactivity
-(void)minCalculation_backgroundtime:(NSString *)backgroundTime forgroundTime:(NSString *)foreGroundTime
{
    NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];
    [dateformat setDateFormat:@"MM/dd/yyyy HH:mm:ss"];

    NSDate *lastDate = [dateformat dateFromString:foreGroundTime];
    NSDate *todaysDate = [dateformat dateFromString:backgroundTime];
    NSTimeInterval lastDiff = [lastDate timeIntervalSinceNow];
    NSTimeInterval todaysDiff = [todaysDate timeIntervalSinceNow];
    NSTimeInterval dateDiff = lastDiff - todaysDiff;
    int min = dateDiff/60;
    NSLog(@"Good to see you after %i minutes",min);
}
于 2013-11-11T16:53:07.833 回答
2

您可以节省NSUSerDefaults进入后台的时间。当您的应用程序回到前台时,您可以获得那个时间的差异。当您的应用程序进入后台时,此方法将执行- (void)applicationDidEnterBackground:(UIApplication *)application,当它返回前台时,- (void)applicationWillEnterForeground:(UIApplication *)application此方法将被调用。

于 2013-11-11T16:54:58.453 回答