Skip to content

Commit f271943

Browse files
committed
fix: possibly fix issues running in the background
Signed-off-by: Tommy van der Vorst <tommy@pixelspark.nl>
1 parent 5106a54 commit f271943

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

Sushitrain/BackgroundManager.swift

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -57,17 +57,9 @@ import BackgroundTasks
5757
self.appState = appState
5858

5959
// Schedule background synchronization task
60-
BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.longBackgroundSyncID, using: nil) { task in
61-
Task { await self.handleBackgroundSync(task: task) }
62-
}
63-
64-
BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.shortBackgroundSyncID, using: nil) { task in
65-
Task { await self.handleBackgroundSync(task: task) }
66-
}
67-
68-
BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.continuedBackgroundSyncID, using: nil) { task in
69-
Task { await self.handleBackgroundSync(task: task) }
70-
}
60+
BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.longBackgroundSyncID, using: nil, launchHandler: self.backgroundLaunchHandler)
61+
BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.shortBackgroundSyncID, using: nil, launchHandler: self.backgroundLaunchHandler)
62+
BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.continuedBackgroundSyncID, using: nil, launchHandler: self.backgroundLaunchHandler)
7163

7264
updateBackgroundRunHistory(appending: nil)
7365
_ = self.scheduleBackgroundSync()
@@ -87,6 +79,17 @@ import BackgroundTasks
8779
try BGTaskScheduler.shared.submit(request)
8880
}
8981

82+
private func backgroundLaunchHandler(_ task: BGTask) {
83+
// This convoluted dance may be necessary to prevent crashing in libdispatch (_dispatch_assert_queue_fail)
84+
// The reason seems to be that the launch handler is called on some thread that is not associated with a queue.
85+
// The fix here is to kick off the task from the main queue
86+
DispatchQueue.main.async {
87+
Task { @MainActor in
88+
await self.handleBackgroundSync(task: task)
89+
}
90+
}
91+
}
92+
9093
func inactivate() {
9194
if self.currentBackgroundTask == nil {
9295
Log.info(

0 commit comments

Comments
 (0)