SPB Git

Repository Public

BackgroundWork.swift 1.9 KB 42 lines swift

1// SP Drive iOS2// File: App/BackgroundWork.swift3// Description: Background refresh and processing (BackgroundTasks). iOS grants these moments when it sees fit; they are used to pull4//              changes, push queued operations and keep transfers moving. Nothing here assumes continuous background execution.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import BackgroundTasks9import Foundation1011enum BackgroundWork {12    /// Must be called before the app finishes launching.13    @MainActor static func register(model: AppModel) {14        BGTaskScheduler.shared.register(forTaskWithIdentifier: AppConfiguration.refreshTaskID, using: nil) { task in run(task, model: model) }15        BGTaskScheduler.shared.register(forTaskWithIdentifier: AppConfiguration.syncTaskID, using: nil) { task in run(task, model: model) }16    }1718    static func schedule() {19        let refresh = BGAppRefreshTaskRequest(identifier: AppConfiguration.refreshTaskID)20        refresh.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)21        try? BGTaskScheduler.shared.submit(refresh)22        let sync = BGProcessingTaskRequest(identifier: AppConfiguration.syncTaskID)23        sync.requiresNetworkConnectivity = true24        sync.requiresExternalPower = false25        sync.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 60)26        try? BGTaskScheduler.shared.submit(sync)27    }2829    private static func run(_ task: BGTask, model: AppModel) {30        nonisolated(unsafe) let task = task31        schedule()32        let work = Task { @MainActor in33            guard model.phase == .signedIn || model.api.isSignedIn else { task.setTaskCompleted(success: true); return }34            await model.start()35            await model.engine.sync()36            await model.checkServerNotifications()37            task.setTaskCompleted(success: !Task.isCancelled)38        }39        task.expirationHandler = { work.cancel() }40    }41}42
Files main
Menu

Theme