gpt4 book ai didi

iphone - 显示应用程序在后台运行的持续时间

转载 作者:行者123 更新时间:2023-11-29 04:01:20 26 4
gpt4 key购买 nike

我是 iOS 编程新手,我正在尝试制作一个非常简单的应用程序来了解更多有关生命周期和不同状态的信息。该应用程序将在应用程序运行时存储当前时间戳,每当它进入后台并重新启动时,它都会显示一条消息,例如“很高兴在 xx 分钟后见到你”。

现在,我的方法是这样的,一开始会有一个时间戳存储在变量中,当调用 viewDidLoad() 方法时,它将检查时间戳与当前时间戳并显示减去的值。

当应用程序进入后台时,我将更改 viewDidUnload() 方法中本地时间戳变量的值,当应用程序返回后台时,我将比较时间戳并显示消息。

关于执行此操作的正确方法有什么指示吗?

最佳答案

在您的 appdelegate.m 文件中使用以下代码

下面写方法

-(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);
}

并替换以下两种方法

- (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 inactive state; here you can undo many of the changes made on entering the background.
}

试试这个你的问题就会解决

关于iphone - 显示应用程序在后台运行的持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15826838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com