【问题标题】:How to perform last actions upon user exiting an iPhone app?如何在用户退出 iPhone 应用程序时执行最后的操作?
【发布时间】:2017-02-21 23:12:11
【问题描述】:

当用户在 iPhone 上终止应用程序时,有没有办法执行一些最后的操作?

在 UIApplicationDelegate 中有 applicationWillTerminate: 但据我了解,不能保证在应用程序终止时调用它。还有其他方法吗?

【问题讨论】:

  • 它会被调用,但用户退出不一定是终止。 willResignActive 会告诉你退出(终止与否)。

标签: ios terminate


【解决方案1】:

你不能依赖 applicationWillTerminate 被调用。来自文档:

对于不支持后台执行或链接到 iOS 3.x 或更早版本的应用程序,当用户退出应用程序时始终调用此方法。对于支持后台执行的应用程序,当用户退出应用程序时通常不会调用此方法,因为在这种情况下应用程序只是移动到后台。但是,在应用程序在后台运行(未挂起)并且系统出于某种原因需要终止它的情况下,可能会调用此方法。

保存任何状态的适当位置是应用程序进入后台时。一旦发生这种情况,就无法知道应用程序是否会返回前台,或者它是否会被杀死然后从头开始。

【讨论】:

  • -applicationWillTerminate: 也将在 iPhone 3G 上调用(支持它很棘手,但并非不可能),并且文档还说“在应用程序运行在后台(未挂起),系统出于某种原因需要终止它”。为避免在添加后台任务/等时被咬,最好两者都支持。
  • @rmaddy 这个答案是否成立,即使在今天?面临与stackoverflow.com/questions/42367803/… 类似的问题,我只想在应用程序终止时显示通知。有什么解决方法吗?
  • @sweta.me 我的回答有点过时了。事情变了。我已经更新了答案。
  • @rmaddy 感谢您更新答案。一个快速的问题:如果您只想在应用程序终止时执行某些操作,您会怎么做?再次感谢您。
  • @sweta.me 你不能,因为不能保证你的应用在终止时会收到通知。
【解决方案2】:

当您使用其中一个项目模板时,所有与您的应用状态相关的方法都在您的 AppDelegate 中。

将代码放在applicationWillResignActive: 方法中。如果您的应用进入非活动状态(终止或否),它将被调用。

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

【讨论】:

    【解决方案3】:

    保存状态的“正确”位置是-applicationDidEnterBackground:-applicationWillTerminate:。不用担心双重储蓄;通常只调用其中一个(IME,-applicationWillTerminate: 在您的应用在后台被杀死时不会被调用)。

    警告-applicationDidEnterBackground:保证会被调用,因为它是在您的应用进入后台后调用的(因此变成有资格在没有通知的情况下被杀!)。如果您的应用程序在后台运行时设备内存不足,它可能会被杀死。避免这种情况的最佳方法是一开始就不要使用太多内存。

    可以使用 -applicationWillResignActive:,但我不建议这样做:应用程序变得非常频繁地处于非活动状态。一个明显的是系统对话框(位置/隐私提示、Wi-Fi、显示为警报、警报的通知)、TWTweetSheet,我怀疑 MFMailComposeViewController、MFMessageComposeViewController、通知中心、应用程序切换栏(例如,更改曲目/启用方向锁定)。

    【讨论】:

      【解决方案4】:

      您可以在 appdelegate 中使用 applicationWillResignActive 方法,或者您可以执行以下操作,如果您想保存内容,但由于某种原因,您不想在 appdelegate 中执行此操作:

      - (void) viewDidLoad/init { 
          [[NSNotificationCenter defaultCenter]
              addObserver:self
              selector:@selector(myApplicationWillResign)
              name:UIApplicationWillResignActiveNotification 
              object:NULL];
      }
      
      - (void) myApplicationWillResign {
          NSLog(@"About to die, perform last actions");
      }
      

      【讨论】:

        猜你喜欢
        • 2012-08-29
        • 1970-01-01
        • 2014-02-16
        • 1970-01-01
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 2011-10-25
        • 1970-01-01
        相关资源
        最近更新 更多