为什么我的iOS应用程序在返回前台模式后从第一个屏幕重新启动



在详细信息屏幕中的我的iOS应用程序中,我按下主页按钮,这将导致它进入后台模式。在大约7分钟的不活动之后,我重新启动它,它不是从我离开的地方开始的。它是从第一个屏幕开始的。

我上网了解了国家的保护和恢复。我在一个屏幕上实现了,但它似乎不起作用。这是我在appDelegate.m 中所做的

//appDelegate.m
-(BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder
{
return YES;
}
-(BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder
{
return YES;
}

以下代码位于willFinishLaunchingWithOptions方法中的appDelegate.m中。我没有使用故事板,因为这个应用程序很旧。它有XIB。因此,该应用程序总是需要转到登录屏幕,在那里检查是否存储了accessToken,它将从登录屏幕转到主屏幕。如果未存储,它将保留在登录屏幕中。因此,这是必须执行的。因此,只有一种方法可以像下面这样对其进行编码。

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
...
loginViewController = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
self.navigationController = [[UINavigationController alloc]initWithRootViewController:loginViewController];
self.navigationController.restorationIdentifier = @"NavigationController";
[loginViewController.view setBackgroundColor:[UIColor whiteColor]];
self.window.rootViewController = self.navigationController;
...
...
}

我已经在viewDidLoad()中为所有视图控制器提供了restorationId,如下所示。例如,这就是我在PetDetailViewController.m 中所做的

- (void)viewDidLoad
{
[super viewDidLoad];
self.restorationIdentifier = @"MatchedPetIdentification";
self.restorationClass = [self class];
}
-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
[super encodeRestorableStateWithCoder:coder];
}
-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
[super decodeRestorableStateWithCoder:coder];
}

现在,当我转到PetDetail屏幕并按下home按钮时,encodeRestorableStateWithCoder()会被调用。从xcode停止应用程序,重新启动它保持在同一屏幕上,但立即转到登录屏幕并转移到主屏幕(willFinishLaunchingWithOptions中的代码可能正在执行)

我做错什么了吗?如何防止应用程序从第一个屏幕重新启动,除非用户手动杀死它?

您无法控制应用程序何时从后台状态进入挂起状态,操作系统将自动执行此操作,以便为前台应用程序提供更多内存。有关状态转换和应用程序终止的更多信息,您可以参考:

https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html

最新更新