- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我使用 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
我的疑问是
beginBackgroundTaskWithExpirationHandler
对剩余时间没有任何影响?applicationEntersBackground
方法返回,类似的通知会被发送到另一个VC的相应方法。假设总延长持续时间为 180 秒,而 VC1 在通知处理上花费了大约 10 秒,VC2 通知处理程序在其 beginBackgroundTaskWithExpirationHandler - endBackgroundTask
调用之间是否有大约 170 秒? 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.
回答您的问题:
backgroundTimeRemaining
保持在 180 左右,因此您可以知道启动后台任务后的时间。该值并不表示您可以在没有后台任务的情况下运行多长时间。beginBackgroundTaskWithExpirationHandler
产生了影响,如您所见,剩余时间减少了(减少了一个很小的值,因为该方法不需要太多时间)beginBackgroundTaskWithExpirationHandler
和调用 endBackgroundTask
之间耗时。只要不超过 180 秒的限制,您就可以根据需要拆分通话之间的时间间隔endBackgroundTask
后,无论用了 2 秒还是 179 秒,应用程序都将被挂起。关于应用程序进入后台的更多细节,您可以找到here .我建议您仔细阅读文档,它可能会澄清您在此事上可能遇到的其他问题。
关于ios - UIApplicationDidEnterBackgroundNotification 剩余执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34736784/
iPhone 应用程序中 UIApplication DidEnterBackgroundNotification 的用途是什么,或者我们如何从中受益 最佳答案 此通知表示用户在 iPhone 4 上
我正在使用: [[NSNotificationCenter defaultCenter] addObserver:self
在我使用 iOS 9.2、Swift 2.1 的应用程序中,当应用程序进入后台时,我需要将一些数据保存到核心数据中。为此,我在 UIApplicationDidEnterBackgroundNotif
我正在使用 Cordova 2.1.0 开发 IOS 应用程序。由于我是应用程序开发的新手,所以我有一个非常基本的问题。 我正在使用 applicationDidEnterBackground 方法在
我有一个播放音频的 UIView,有一个 NSTimer 和进度条动画。 为简单起见,如果用户切换应用程序或接听电话,我希望所有进程都停止并自行重置。 我建议使用: 调用观察者 - 可能在 viewW
我正在创建播放 youtube 视频的应用。 在这个应用程序中, 用户可以播放 youtube 视频,当用户进入后台或锁定手机时,将播放视频的声音 我正在使用 UIApplicationDidEnte
我将一个文件复制到一个新项目中,它似乎工作正常。这段代码也在旧项目中工作,但突然之间(在新项目中),我遇到了几个我无法弄清楚的错误。 NSNotificationCenter *center = [N
我是一名优秀的程序员,十分优秀!