gpt4 book ai didi

ios - app进入suspended状态前执行后台任务

转载 作者:可可西里 更新时间:2023-11-01 02:02:04 25 4
gpt4 key购买 nike

我正在尝试在我的应用程序中执行有限长度后台任务。但是,截至目前,我的代码在应用程序暂停之前没有执行。

我遵循了相当多的教程,这些教程声称以下内容是正确的,但显然我弄错了。相关代码应发布在下面(如果我遗漏了什么,请要求任何澄清):

class Manager {

private var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid

init(){
// Add observer able of detecting when app will go to background
NotificationCenter.default.addObserver(self, selector: #selector(self.didEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
}

deinit {
// Observers removed when view controller is dismissed / deallocated
NotificationCenter.default.removeObserver(self)
}

// Routine performed when app will resign from active
@objc private func didEnterBackground(_ notification: Notification){

registerBackgroundTask()

// Code that needs to be executed before app is suspended ------
DispatchQueue.global().sync {

self.isBackgrounding = true

self.shutdownSession()


self.isConnected = false
self.isActivated = false
self.activate = false

self.connectionManager.closeConnectionToPeripherals()

}
// -----------------------------------------------------
self.endBackgroundTask()

}

func registerBackgroundTask() {
backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
self?.endBackgroundTask()
}
assert(backgroundTask != UIBackgroundTaskInvalid)
}

func endBackgroundTask() {
print("\n\n\nBackground task ended.\n\n\n")
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}

}

我遇到一个问题,后台任务似乎总是在执行代码之前结束。如何确保我的同步块(synchronized block)中的代码在应用挂起之前得到执行?

我也不太理解“registerBackgroundTask()”——尽管互联网坚持以这种方式实现它——因为它调用了 endBackgroundTask()。

最佳答案

您需要将 self.endBackgroundTask() 调用移动到您的 DispatchQueue block 中,就在 self.connectionManager.closeConnectionToPeripherals() 之后。

registerBackgroundTask 方法不会直接调用self.endBackgroundTask(),而是仅在后台任务过期时调用。通常,如果您的应用在后台约 30 秒后未完成任务,就会发生这种情况。

关于ios - app进入suspended状态前执行后台任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45568744/

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