我正在开发一个依赖会话并基于会话生命周期工作的应用程序:
当用户启动应用时,会话开始。
当用户终止该应用时会话结束。
这是一个非常简单和基本的概念,但我在实施它时遇到了麻烦。
问题是此方法不可靠,可能无法调用:
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
在多任务处理期间会调用其他 AppDelegate 方法,因为它们与开头或结束会议。 (即使这就是我现在正在使用的)
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// 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
{
// 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.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
以下是我尝试的内容:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
static BOOL firstTime = YES;
if (firstTime) {
NSLog(@"First time!");
firstTime = NO;
}
else {
NSLog(@"Not first time...");
}
}
以下两个例子不起作用:
让我们说电池电量耗尽,设备关机。下次启动应用程序时,它将被视为首次启动,即使它不是。只有在用户终止它之后才会被认为是第一次启动。
应用程序崩溃,下次启动它时会被视为首次启动,但会话尚未结束。崩溃不是用户终止。
我不知道自己是否达到了死胡同状态,这就是我寻求帮助的原因。
提前致谢!
编辑:我正在寻找一种方法来随时了解用户从多任务中删除应用的时间。如果应用程序崩溃,或手机电池耗尽或由于任何其他原因而被终止,除非用户在多任务中刷了一下这对我很好......
答案 0 :(得分:3)
我没有解决方案,我确定没有解决方案。据我所知,没有办法做到这一点,因为操作系统可能会选择停止你的应用程序冷。没有任何机会执行任何代码。例如,unix kill命令会执行此操作。你可以注册信号处理程序,但根据杀戮是什么,它们仍然可能无法运行。 Apple可能不接受您的应用。
我从您的解释中假设您正在尝试在服务器上维护某种会话。如果是这种情况,那么我认为您需要从尝试在设备上管理它到在服务器上管理它。可能有某种不活动超时。
然而,我真正考虑的是将会话管理切换到活动边界。这意味着只有一个会话,当你的应用程序处于活动状态时会更可靠。
最终,无国籍人才是最佳选择。尽可能避免会话将创建一个更加可靠和简单的应用程序。
答案 1 :(得分:0)
维持此类会话的唯一方法是使用application:willFinishLaunchingWithOptions:
或application:didFinishLaunchingWithOptions:
结束上一个会话并开始新会话。
这确实意味着“会话”可能会持续很长时间,但这是选择会话的定义时与操作系统允许的内容不匹配的错误。