无法启动beginBackgroundTask SWIFT 3
对不起我坚持,但我试图启动后台任务(XCode8,迅疾3)无法启动beginBackgroundTask SWIFT 3
在AppDelegate.swift:
func applicationDidEnterBackground(_ application: UIApplication) {
var bgTask: UIBackgroundTaskIdentifier = 0;
bgTask = application.beginBackgroundTask(withName:"MyBackgroundTask", expirationHandler: {() -> Void in
print("The task has started")
application.endBackgroundTask(bgTask)
bgTask = UIBackgroundTaskInvalid
})
}
该应用程序从未显示“任务已启动”消息。我究竟做错了什么?
到期处理程序块在一段时间后(通常5分钟左右)被调用。 这是为了用来写清理逻辑,如果你的后台任务需要花费很多时间来完成。
您的代码没有任何问题,您只需要在后台中等待以使后台任务过期。
您对后台任务的使用是错误的。它应该是这样的:
func applicationDidEnterBackground(_ application: UIApplication) {
var finished = false
var bgTask: UIBackgroundTaskIdentifier = 0;
bgTask = application.beginBackgroundTask(withName:"MyBackgroundTask", expirationHandler: {() -> Void in
// Time is up.
if bgTask != UIBackgroundTaskInvalid {
// Do something to stop our background task or the app will be killed
finished = true
}
})
// Perform your background task here
print("The task has started")
while !finished {
print("Not finished")
// when done, set finished to true
// If that doesn't happen in time, the expiration handler will do it for us
}
// Indicate that it is complete
application.endBackgroundTask(bgTask)
bgTask = UIBackgroundTaskInvalid
}
另外请注意,你应该要保持运行,即使应用程序进入后台一个短的时间内任何一类使用beginBackgroundTask/endBackgroundTask
周围的任何代码。
@maddy - 你说得对,但我不明白应该在expirationHandler中执行哪段代码。 – Alex
@rmaddy是不是你的代码不正确?我的意思是,如果有这样的印刷线需要20分钟。 (在这里它不会发生),然后从expirationHandler,你不会调用'application.endBackgroundTask(bgTask)',那会导致崩溃... – Honey
@Honey这是过期处理程序的用途。看到我的评论“做点什么来阻止......”? “做某事”是做一些事情,阻止任何过度长时间运行的后台任务。很显然'print'不会太长。但是,假设你有一个“while”循环时间过长。过期处理程序需要设置一个在'while'循环中检查的变量,以便'while'循环在下一次迭代时停止。至少这是一个例子。 – rmaddy
我认为expirationHandler只是在后台任务完成后立即执行。 – Christoph
@Christoph无论如何,信息应该出现 – Alex