正如标题所说:我如何确定我的iOS App关闭了多长时间或已经在后台?我需要知道这个,因为如果应用程序已经关闭或已经在后台工作超过3个小时,我想调用一个方法。
答案 0 :(得分: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);
}
答案 1 :(得分:2)
您可以节省NSUSerDefaults
的时间,以便在后台进行。当您的应用程序返回前台时,您可以获得该时间的差异。
当您的应用程序进入后台时,此方法将执行- (void)applicationDidEnterBackground:(UIApplication *)application
,当它返回到前台- (void)applicationWillEnterForeground:(UIApplication *)application
时,此方法将被调用。