【问题标题】:why my iOS app restarts from first screen after coming back to foreground mode?为什么我的 iOS 应用程序在返回前台模式后会从第一个屏幕重新启动?
【发布时间】:2018-03-22 20:21:09
【问题描述】:

当在详细屏幕中的我的 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 方法中。我没有使用故事板,因为这个应用程序很旧。它有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 屏幕并按下主页按钮时,将调用 encodeRestorableStateWithCoder()。从 xcode 停止应用程序,重新启动它会停留在同一屏幕上,但会立即进入登录屏幕并转移到主屏幕(willFinishLaunchingWithOptions 中的代码可能正在执行)

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

【问题讨论】:

  • 查看是否在 viewWillEnterForeground 或 didBecomeActive 方法中编写了要重置的内容。此外,您可能需要检查应用程序的内存占用。您的应用可能由于某种原因被系统杀死。
  • @PuneetSharma 谢谢。当应用程序激活时,它实际上是在重置东西。有什么方法可以查明为什么系统会在几分钟后在后台杀死我的应用程序?
  • @HirenPrajapati 如果每个应用程序处于后台模式超过 3 分钟并且操作系统需要更多内存用于其他应用程序,则每个应用程序都会被杀死。
  • @HirenPrajapati:因为你在 didBecomeActive 中重置了东西,所以每次 ypu 将应用程序移动到前台时都会调用它,你怎么说应用程序在挂起状态下被杀死?
  • @PuneetSharma 每个人都说 iOS 会在应用程序进入后台几分钟后暂停应用程序。

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


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
相关资源
最近更新 更多