防止 iOS 几分钟后杀死 App

Prevent iOS from killing App after a few minutes

我想防止 iOS 在几分钟后杀死我的应用程序。 我已经在 SO: 上阅读了这个线程。它说如果我没有超过 3 分钟的后台任务,我的应用程序就不会被杀死。有人可以验证这是真的吗?因为我的后台任务不会 运行 超过 3 分钟,即使我的应用程序在这段时间后被杀死。 我的后台任务是一个更新小部件的计时器。这是一些代码:

self.backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
        self?.endBackgroundTask()
//endBackGroundTask looks like this
UIApplication.shared.endBackgroundTask(self.backgroundTask)
    self.backgroundTask = UIBackgroundTaskInvalid
//
    }
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self,   selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)

.

// at the beginning of the class
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid

.

// in viewWillDisappear
self.timer.invalidate()
    if self.backgroundTask != UIBackgroundTaskInvalid {
        self.endBackgroundTask()

    }

简短回答:您不能 运行 后台任务超过 3 分钟,除非您是精细导航应用程序或音频播放器。 Apple 不允许这样做。

您的后台任务是一个 运行 超过 3 分钟的计时器。所以你的应用程序被正确地杀死了。认为它已确认,因为这是 Apple 的设计。

杀死应用程序的不是计时器正在执行的操作,而是计时器本身。

您可以阅读 Apple's Documentation 了解更多信息。

Always try to avoid doing any background work unless doing so improves the overall user experience. An app might move to the background because the user launched a different app or because the user locked the device and is not using it right now. In both situations, the user is signaling that your app does not need to be doing any meaningful work right now. Continuing to run in such conditions will only drain the device’s battery and might lead the user to force quit your app altogether. So be mindful about the work you do in the background and avoid it when you can.

您需要构建您的应用程序,使其不需要在后台持续执行。据我了解,您的应用程序会显示一个倒数计时器,并且可以在 Today Widget 中显示相同的倒数计时器。我将使用的方法如下:

  • 在用户默认设置中存储定时器的 "end date" 以与您的小部件共享
  • 当您的应用程序位于前台时,使用 Timer 定期更新您的 UI
  • 显示您的小部件时,请在小部件中使用 Timer 定期更新其 UI
  • 当您的应用移至后台时,为到期时间安排本地通知
  • 当您的应用移回前台时,如果该预定通知尚未触发,您可以取消它。
  • 支持合法终止应用(如内存压力或长时间挂起)的应用恢复

如果你这样做,那么你永远不需要调用 beginBackgroundTask。如果您在进入后台后的 3 分钟内确实调用了 beginBackgroundTask 而没有调用 endBackgroundTask,那么您的应用将被终止,即使您没有使用任何 CPU.