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

时间:2017-10-11 08:31:23

标签: ios application-restart state-restoration uikit-state-preservation ios-background-mode

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

我上网了解了国家保护和恢复。我在一个屏幕上实现但它似乎不起作用。这就是我在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()中将restoreId提供给所有视图控制器,如下所示。例如,这就是我在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中的代码可能正在执行)

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

1 个答案:

答案 0 :(得分:1)

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

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