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

Hir*_*ati 6 application-restart ios uikit-state-preservation state-restoration ios-background-mode

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

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

    //appDelegate.m

    -(BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder
    {
        return YES;
    }

    -(BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder
    {
        return YES;
    }
Run Code Online (Sandbox Code Playgroud)

以下代码位于 appDelegate.m 中的 willFinishLaunchingWithOptions 方法中。我没有使用故事板,因为这个应用程序很旧。它有 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;
   ...
   ...
}
Run Code Online (Sandbox Code Playgroud)

我已经在 viewDidLoad() 中为所有视图控制器提供了恢复 ID,如下所示。例如这是我在 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];
    }
Run Code Online (Sandbox Code Playgroud)

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

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

小智 1

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

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