feat: iOS syncs when BGTaskScheduler lets it (notifications, Phase 11)

A refresh task runs the quick pass with 25 seconds and a processing task
the full one with eight minutes, both registered by an app delegate that
also forwards notification taps. Written on linux: none of the Swift or
iosMain code has been compiled; it needs a mac before it can be trusted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 12:59:29 +02:00
1 parent a60f6b937e
commit 51c2423ab6
3 files changed
+157 -1

No files matched your search

@@ -0,0 +1,61 @@
package mobi.giza.compose
import kotlin.concurrent.atomics.AtomicInt
import kotlin.concurrent.atomics.ExperimentalAtomicApi
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import mobi.giza.compose.managers.BackgroundSyncPass
import platform.UIKit.UIApplication
import platform.UIKit.UIApplicationState
/** What Swift holds while a pass runs, to cancel it when iOS takes the time back. */
class BackgroundSyncHandle internal constructor(private val job: Job) {
fun cancel() = job.cancel()
}
/** Whether to ask iOS for background time at all. docs/notifications-and-background-sync.md, D12. */
fun backgroundSyncEnabled(): Boolean = ExperimentalFeatures.backgroundSync
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
/**
* Runs the pass for a BGTaskScheduler task and reports once, through [onDone], whether it got to the
* end: a refresh ([quick]) with 25 seconds, under the thirty iOS grants; a processing task with
* eight minutes. Called from `iOSApp.swift`. Not compiled on the linux host this was written on.
*/
@OptIn(ExperimentalAtomicApi::class)
fun startBackgroundSync(quick: Boolean, onDone: (Boolean) -> Unit): BackgroundSyncHandle {
val reported = AtomicInt(0)
fun report(success: Boolean) {
if (reported.compareAndSet(0, 1)) onDone(success)
}
if (!ExperimentalFeatures.backgroundSync) {
report(true)
return BackgroundSyncHandle(Job().apply { complete() })
}
// A task launched cold has no screen, and AppLifecycle defaults to visible -- which the pass
// reads as "the foreground already covers it".
if (UIApplication.sharedApplication.applicationState == UIApplicationState.UIApplicationStateBackground) {
AppLifecycle.enteredBackground()
}
val job = scope.launch {
try {
val outcome = gizaRuntime().backgroundSync.run(
kind = if (quick) BackgroundSyncPass.Kind.Quick else BackgroundSyncPass.Kind.Full,
deadline = if (quick) 25.seconds else 8.minutes,
)
report(outcome == BackgroundSyncPass.Outcome.Completed || outcome == BackgroundSyncPass.Outcome.Visible)
} finally {
report(false)
}
}
return BackgroundSyncHandle(job)
}
+12
View File
@@ -4,5 +4,17 @@
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<!-- Syncing while closed: a short refresh when iOS chooses, and a longer one overnight.
docs/notifications-and-background-sync.md, Phase 11. -->
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>processing</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>mobi.giza.refresh</string>
<string>mobi.giza.sync</string>
</array>
</dict>
</plist>
+84 -1
View File
@@ -1,10 +1,93 @@
import SwiftUI
import BackgroundTasks
import UserNotifications
import ComposeApp
/// Registers the background tasks before launch finishes, as BGTaskScheduler requires, and
/// receives notification taps. docs/notifications-and-background-sync.md, Phases 6 and 11.
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
UNUserNotificationCenter.current().delegate = self
BackgroundSync.register()
return true
}
/// The dispatcher already decided this should be shown, including that it is not for the
/// room on screen, so a notification that arrives in front is shown as it would be behind.
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
completionHandler([.banner, .list, .sound])
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
PlatformNotifier_iosKt.notificationTapped(userInfo: response.notification.request.content.userInfo)
completionHandler()
}
}
/// The two tasks: a quick refresh and a longer processing run, each the Kotlin pass with its own
/// deadline. Rescheduled every time one runs and every time the app leaves the screen.
enum BackgroundSync {
static let refresh = "mobi.giza.refresh"
static let processing = "mobi.giza.sync"
static func register() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: refresh, using: nil) { task in
handle(task, quick: true)
}
BGTaskScheduler.shared.register(forTaskWithIdentifier: processing, using: nil) { task in
handle(task, quick: false)
}
}
static func schedule() {
guard BackgroundSync_iosKt.backgroundSyncEnabled() else { return }
let refreshRequest = BGAppRefreshTaskRequest(identifier: refresh)
refreshRequest.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
try? BGTaskScheduler.shared.submit(refreshRequest)
let processingRequest = BGProcessingTaskRequest(identifier: processing)
processingRequest.requiresNetworkConnectivity = true
processingRequest.requiresExternalPower = false
try? BGTaskScheduler.shared.submit(processingRequest)
}
private static func handle(_ task: BGTask, quick: Bool) {
schedule()
let running = BackgroundSync_iosKt.startBackgroundSync(quick: quick) { success in
task.setTaskCompleted(success: success.boolValue)
}
task.expirationHandler = {
running.cancel()
}
}
}
@main
struct iOSApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
ContentView()
}
.onChange(of: scenePhase) { phase in
if phase == .background {
BackgroundSync.schedule()
}
}
}
}
}