gpt4 book ai didi

ios - UIApplicationDidEnterBackgroundNotification 剩余执行时间

转载 作者:行者123 更新时间:2023-11-28 08:48:10 25 4
gpt4 key购买 nike

在我使用 iOS 9.2、Swift 2.1 的应用程序中,当应用程序进入后台时,我需要将一些数据保存到核心数据中。为此,我在 UIApplicationDidEnterBackgroundNotification 通知的调用路径中注册了每个 View Controller ,每个 View Controller 都有一个实例方法来保存各自的数据。

我在多个地方读到,默认情况下,应用程序需要大约 5 秒才能完成执行,因此我们需要使用 beginBackgroundTaskWithExpirationHandler 将其延长到大约 5 分钟。以下是响应上述通知的选择器方法的示例。

func applicationEntersBackground()
{
print("Before Extension: \(UIApplication.sharedApplication().backgroundTimeRemaining)")

let taskID = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(nil)

print("During Extension: \(UIApplication.sharedApplication().backgroundTimeRemaining)")

saveCoreData()

if(taskID != UIBackgroundTaskInvalid)
{
UIApplication.sharedApplication().endBackgroundTask(taskID)
}

print("After Extension: \(UIApplication.sharedApplication().backgroundTimeRemaining)")
}

以下是print()语句的结果

Before Extension: 179.933103708318
During Extension: 179.930266333336
After Extension: 179.922843541659

我的疑问是

  1. 为什么在我请求延长时间之前剩余时间大约是 180 秒?我尝试了多次。它总是接近 180 秒,而不是建议的 5 秒。
  2. 为什么调用 beginBackgroundTaskWithExpirationHandler 对剩余时间没有任何影响?
  3. 一旦一个VC的applicationEntersBackground方法返回,类似的通知会被发送到另一个VC的相应方法。假设总延长持续时间为 180 秒,而 VC1 在通知处理上花费了大约 10 秒,VC2 通知处理程序在其 beginBackgroundTaskWithExpirationHandler - endBackgroundTask 调用之间是否有大约 170 秒?
  4. 在不同 VC 的通知处理程序的连续调用之间,显然有一段很短的扩展请求不活动的时间。在这种情况下,时间安排如何? 5 秒计数器(假设为真)是否会在 endBackgroundTask 调用后立即恢复,并可能在下一个 VC 收到通知之前终止应用程序?

感谢任何帮助。

最佳答案

通过查看 documentation对于 backgroundTimeRemaining:

While the app is running in the foreground, the value in this property remains suitably large. If the app starts one or more long-running tasks using the beginBackgroundTaskWithExpirationHandler: method and then transitions to the background, the value of this property is adjusted to reflect the amount of time the app has left to run.

回答您的问题:

    当应用程序处于前台时,
  1. backgroundTimeRemaining 保持在 180 左右,因此您可以知道启动后台任务后的时间。该值并不表示您可以在没有后台任务的情况下运行多长时间。
  2. beginBackgroundTaskWithExpirationHandler 产生了影响,如您所见,剩余时间减少了(减少了一个很小的值,因为该方法不需要太多时间)
  3. 这里重要的是调用 beginBackgroundTaskWithExpirationHandler 和调用 endBackgroundTask 之间耗时。只要不超过 180 秒的限制,您就可以根据需要拆分通话之间的时间间隔
  4. 调用 endBackgroundTask 后,无论用了 2 秒还是 179 秒,应用程序都将被挂起。

关于应用程序进入后台的更多细节,您可以找到here .我建议您仔细阅读文档,它可能会澄清您在此事上可能遇到的其他问题。

关于ios - UIApplicationDidEnterBackgroundNotification 剩余执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34736784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com