Open History to see the last commit
1import BackgroundTasks
2import Foundation
3
4@MainActor
5final class PlatformBackgroundRefreshCoordinator {
6 typealias RefreshAction = @MainActor @Sendable () async -> Bool
7
8 static let shared = PlatformBackgroundRefreshCoordinator()
9 static var identifier: String {
10 "\(Bundle.main.bundleIdentifier ?? "com.t3tools.t3code.swiftui").refresh"
11 }
12
13 private var refreshAction: RefreshAction?
14 private var isRegistered = false
15
16 func install(refreshAction: @escaping RefreshAction) {
17 self.refreshAction = refreshAction
18 }
19
20 func register() {
21 guard !isRegistered else { return }
22 isRegistered = BGTaskScheduler.shared.register(
23 forTaskWithIdentifier: Self.identifier,
24 using: nil
25 ) { task in
26 guard let refreshTask = task as? BGAppRefreshTask else {
27 task.setTaskCompleted(success: false)
28 return
29 }
30 Task { @MainActor in
31 await Self.shared.handle(refreshTask)
32 }
33 }
34 }
35
36 func schedule() {
37 guard isRegistered else { return }
38 let request = BGAppRefreshTaskRequest(identifier: Self.identifier)
39 request.earliestBeginDate = Date().addingTimeInterval(
40 PlatformBackgroundRefreshPolicy.minimumDelay
41 )
42 try? BGTaskScheduler.shared.submit(request)
43 }
44
45 private func handle(_ task: BGAppRefreshTask) async {
46 schedule()
47 guard let refreshAction else {
48 task.setTaskCompleted(success: false)
49 return
50 }
51
52 // Install cancellation before creating the operation. If expiration
53 // wins the race, `install` immediately cancels the new task.
54 let cancellation = PlatformBackgroundRefreshCancellation()
55 task.expirationHandler = {
56 cancellation.cancel()
57 }
58 let operation = Task { @MainActor in
59 await refreshAction()
60 }
61 cancellation.install(operation)
62 let succeeded = await operation.value
63 task.setTaskCompleted(success: succeeded && !operation.isCancelled)
64 }
65}
66
67private final class PlatformBackgroundRefreshCancellation: @unchecked Sendable {
68 private let lock = NSLock()
69 private var operation: Task<Bool, Never>?
70 private var didExpire = false
71
72 func install(_ operation: Task<Bool, Never>) {
73 let shouldCancel = lock.withLock {
74 self.operation = operation
75 return didExpire
76 }
77 if shouldCancel { operation.cancel() }
78 }
79
80 func cancel() {
81 let operation = lock.withLock {
82 didExpire = true
83 return self.operation
84 }
85 operation?.cancel()
86 }
87}
88
89enum PlatformBackgroundRefreshPolicy {
90 /// iOS chooses the actual cadence. Fifteen minutes is merely the earliest
91 /// useful retry and avoids repeatedly asking the scheduler for immediate work.
92 static let minimumDelay: TimeInterval = 15 * 60
93}