diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundSync.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundSync.ios.kt new file mode 100644 index 00000000..f7321b8a --- /dev/null +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/BackgroundSync.ios.kt @@ -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) +} diff --git a/iosApp/iosApp/Info.plist b/iosApp/iosApp/Info.plist index 11845e1d..fc55473c 100644 --- a/iosApp/iosApp/Info.plist +++ b/iosApp/iosApp/Info.plist @@ -4,5 +4,17 @@ CADisableMinimumFrameDurationOnPhone + + UIBackgroundModes + + fetch + processing + + BGTaskSchedulerPermittedIdentifiers + + mobi.giza.refresh + mobi.giza.sync + diff --git a/iosApp/iosApp/iOSApp.swift b/iosApp/iosApp/iOSApp.swift index d83dca61..ff1ba0c8 100644 --- a/iosApp/iosApp/iOSApp.swift +++ b/iosApp/iosApp/iOSApp.swift @@ -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() + } + } } -} \ No newline at end of file +}