在用背景任务框架编写SwiftUI应用程序时,我得到的结果不一致。我只想提出快速的网络请求,所以我选择使用BGAppRefreshTask。
在签名和功能中设置了后台获取和后台处理。已设置允许的后台任务调度程序标识符。在调试中手动调用它可以在实际设备上正常工作,但在生产中则不会。
我测试了BGAppRefreshTask和BGProcessingTask。我注意到BGProcessingTask正在被调用,但只有当连接到电源时才被调用。我从未见过BGAppRefreshTask的任何更新。我不确定我是不是错过了一些简单的东西。
自从更新这篇文章以来,BGAppRefreshTask还没有为运行过四天。BGProcessingTask在一夜之间运行了13次,但前提是我的设备正在充电。即使将requiresExternalPower设置为false时也是如此。
BGAppRefreshTask run: 0 & BGProcessingTask run: 13
使用命令这里调用调试器是有效的,但它在我的设备上运行时必须在调试器中进行模拟。
(lldb) e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.bgapp.refresh"]
2022-02-26 11:41:33.964753-0800 BGAppRefreshTask[9180:2203525] Simulating launch for task with identifier com.bgapp.refresh
2022-02-26 11:41:35.908739-0800 BGAppRefreshTask[9180:2203542] Starting simulated task: <decode: missing data>
2022-02-26 11:41:35.912108-0800 BGAppRefreshTask[9180:2203542] Marking simulated task complete: <BGAppRefreshTask: com.bgapp.refresh>
Received completion: finished.更新
我使用getPendingTaskRequests查看是否注册了任何任务,很明显,它正在执行,但仍未执行。最早的日期是19:28,所以7:28PM。我在11:23注册了我的任务,但是没有计划运行另一个8小时。
Pending task requests: [<BGAppRefreshTaskRequest: com.bgapp.refresh, earliestBeginDate: 2022-02-28 19:28:34 +0000>]BGAppRefresh
/*!
BGAppRefreshTask
@abstract A background task used to update your app's contents in the background.
*/
class BGADelegate: NSObject, UIApplicationDelegate, ObservableObject {
let taskIdentifier = "com.bgapp.refresh"
@AppStorage("backgroundtask") var tasks: Int = 0
func application(_ applicatiown: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
register()
scheduleAppRefresh()
return true
}
func register() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifier, using: nil) { task in
self.handleAppRefresh(task: task as! BGAppRefreshTask)
print("register")
}
}
func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: taskIdentifier)
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}
func handleAppRefresh(task: BGAppRefreshTask) {
scheduleAppRefresh()
task.expirationHandler = {
task.setTaskCompleted(success: false)
}
DispatchQueue.main.async {
self.tasks += 1
}
// Network request here
task.setTaskCompleted(success: true)
print("handle app refresh")
}
}BGProcessingTask
/*!
BGProcessingTask
@abstract A background task used to perform deferrable processing.
*/
class BGPDelegate: NSObject, UIApplicationDelegate, ObservableObject {
let taskIdentifier = "com.bgapp.refresh"
@AppStorage("backgroundtask") var tasks: Int = 0
func application(_ applicatiown: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
register()
scheduleAppRefresh()
return true
}
func register() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifier, using: nil) { task in
self.handleAppRefresh(task: task as! BGProcessingTask)
print("register")
}
}
func scheduleAppRefresh() {
let request = BGProcessingTaskRequest(identifier: taskIdentifier)
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
request.requiresNetworkConnectivity = true
request.requiresExternalPower = false // Default value in false
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}
func handleAppRefresh(task: BGProcessingTask) {
scheduleAppRefresh()
task.expirationHandler = {
task.setTaskCompleted(success: false)
}
DispatchQueue.main.async {
self.backgroundtask += 1
}
// Network request here
task.setTaskCompleted(success: true)
print("handle app refresh")
}
}发布于 2022-02-28 19:52:58
因此,根据对Background Tasks的新理解,我知道现在它正在被排定为最早的日期,但我正在打开这个应用程序,将它的日期设置为预定日期。当重新启动应用程序时,我没有等待超过预定的较早日期。设置后台应用程序刷新任务时,每个任务都将被覆盖。
struct BGAppRefreshTaskApp: App {
@UIApplicationDelegateAdaptor var delegate: AppDelegate
@Environment(\.scenePhase) var scenePhase
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(delegate)
.onChange(of: scenePhase) { phase in
switch phase {
case .background:
delegate.scheduleAppRefresh()
delegate.background += 1
print("background")
case .active:
print("active")
BGTaskScheduler.shared.getPendingTaskRequests(completionHandler: { request in
print("Pending task requests: \(request)")
})
case .inactive:
print("inactive")
@unknown default:
break
}
}
}
}
}https://stackoverflow.com/questions/71271459
复制相似问题