当我在详细信息屏幕中的 My iOS 应用程序中按下主页按钮时,这将导致它进入后台模式。在大约 7 分钟不活动后,我重新启动它,但它并没有从我离开的地方开始。它从第一个屏幕开始。
我上网了解了国家保护和恢复。我在一个屏幕上实现,但它似乎不起作用。这就是我在 appDelegate.m 中所做的
//appDelegate.m
-(BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder
{
return YES;
}
-(BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder
{
return YES;
}
以下代码在 appDelegate.m 中的 willFinishLaunchingWithOptions 方法中。我没有使用 Storyboard,因为这个应用程序很旧。它有 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() 中为所有 View Controller 提供了 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 屏幕并按下主页按钮时,会调用 encodeRestorableStateWithCoder()。从 xcode 停止应用程序,重新启动它保持在同一屏幕上,但立即转到登录屏幕并转换到主屏幕(willFinishLaunchingWithOptions 中的代码可能正在执行)
我做错了什么吗?如何防止应用程序从第一个屏幕重新启动,除非用户手动终止它?
最佳答案
您无法控制您的应用程序何时从后台状态进入挂起状态,操作系统会自动执行此操作以便为前台应用程序留出更多内存。有关状态转换和应用终止的更多信息,您可以引用:
关于ios - 为什么我的 iOS 应用程序在返回前台模式后从第一个屏幕重新启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46683463/