155 lines
5.6 KiB
Swift
155 lines
5.6 KiB
Swift
import BackgroundTasks
|
|
import UIKit
|
|
|
|
/// Keeps the app running while games download.
|
|
///
|
|
/// In front, the screen is kept awake. Behind another app, iOS 26 and later
|
|
/// can let a long piece of work the person started carry on, and shows its
|
|
/// progress itself; when it will not, or on an older iOS, the app gets a
|
|
/// short while and is then told its time is up.
|
|
@MainActor
|
|
final class BackgroundKeeper {
|
|
/// The app's time in the background ran out: stop cleanly.
|
|
var onTimeUp: (() -> Void)?
|
|
/// The app is in front again.
|
|
var onReturn: (() -> Void)?
|
|
|
|
private var working = false
|
|
private var title = ""
|
|
private var grace = UIBackgroundTaskIdentifier.invalid
|
|
private var observers: [NSObjectProtocol] = []
|
|
|
|
init() {
|
|
let center = NotificationCenter.default
|
|
observers.append(center.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in
|
|
MainActor.assumeIsolated { self?.wentBehind() }
|
|
})
|
|
observers.append(center.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in
|
|
MainActor.assumeIsolated {
|
|
self?.endGrace()
|
|
self?.onReturn?()
|
|
}
|
|
})
|
|
}
|
|
|
|
func workBegan(named name: String) {
|
|
title = "Downloading \(name)"
|
|
working = true
|
|
UIApplication.shared.isIdleTimerDisabled = true
|
|
requestLongRun()
|
|
retitleLongRun()
|
|
if UIApplication.shared.applicationState == .background { wentBehind() }
|
|
}
|
|
|
|
/// `fraction` is nil while the size of the work is not known yet.
|
|
func progressed(to fraction: Double?) {
|
|
reportLongRun(fraction ?? 0)
|
|
}
|
|
|
|
func workEnded(success: Bool) {
|
|
working = false
|
|
UIApplication.shared.isIdleTimerDisabled = false
|
|
finishLongRun(success: success)
|
|
endGrace()
|
|
}
|
|
|
|
// MARK: The short while every app gets
|
|
|
|
private func wentBehind() {
|
|
guard working, grace == .invalid, !hasLongRun else { return }
|
|
grace = UIApplication.shared.beginBackgroundTask(withName: "Steam download") { [weak self] in
|
|
MainActor.assumeIsolated {
|
|
guard let self else { return }
|
|
if !self.hasLongRun { self.onTimeUp?() }
|
|
self.endGrace()
|
|
}
|
|
}
|
|
}
|
|
|
|
private func endGrace() {
|
|
guard grace != .invalid else { return }
|
|
UIApplication.shared.endBackgroundTask(grace)
|
|
grace = .invalid
|
|
}
|
|
|
|
// MARK: The long run iOS 26 can grant
|
|
|
|
#if targetEnvironment(macCatalyst)
|
|
private var hasLongRun: Bool { false }
|
|
private func requestLongRun() {}
|
|
private func retitleLongRun() {}
|
|
private func reportLongRun(_ fraction: Double) {}
|
|
private func finishLongRun(success: Bool) {}
|
|
#else
|
|
/// The granted task; typed loosely because the class only exists from iOS 26.
|
|
private var longRun: AnyObject?
|
|
private var asked = false
|
|
private var registered = false
|
|
|
|
private var hasLongRun: Bool { longRun != nil }
|
|
|
|
/// Info.plist permits "<bundle id>.download.*"; this is the one name used under it.
|
|
private var identifier: String? {
|
|
let permitted = Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String] ?? []
|
|
return permitted.first { $0.hasSuffix(".download.*") }.map { String($0.dropLast()) + "games" }
|
|
}
|
|
|
|
private func requestLongRun() {
|
|
guard #available(iOS 26.0, *), longRun == nil, !asked, let identifier else { return }
|
|
if !registered {
|
|
registered = BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: .main) { [weak self] task in
|
|
MainActor.assumeIsolated {
|
|
guard let self, let granted = task as? BGContinuedProcessingTask else {
|
|
task.setTaskCompleted(success: false)
|
|
return
|
|
}
|
|
self.granted(granted)
|
|
}
|
|
}
|
|
guard registered else { return }
|
|
}
|
|
let request = BGContinuedProcessingTaskRequest(identifier: identifier, title: title, subtitle: "Steam Downloader")
|
|
// If iOS cannot start it now, there is no point in it starting later.
|
|
request.strategy = .fail
|
|
asked = (try? BGTaskScheduler.shared.submit(request)) != nil
|
|
}
|
|
|
|
@available(iOS 26.0, *)
|
|
private func granted(_ task: BGContinuedProcessingTask) {
|
|
asked = false
|
|
guard working else {
|
|
task.setTaskCompleted(success: true)
|
|
return
|
|
}
|
|
longRun = task
|
|
task.progress.totalUnitCount = 1000
|
|
task.expirationHandler = { [weak self] in
|
|
Task { @MainActor in
|
|
guard let self else { return }
|
|
self.onTimeUp?()
|
|
self.finishLongRun(success: false)
|
|
}
|
|
}
|
|
endGrace()
|
|
}
|
|
|
|
private func reportLongRun(_ fraction: Double) {
|
|
guard #available(iOS 26.0, *), let task = longRun as? BGContinuedProcessingTask else { return }
|
|
task.progress.completedUnitCount = Int64((fraction * 1000).rounded())
|
|
}
|
|
|
|
/// The next game in the queue takes over the same grant.
|
|
private func retitleLongRun() {
|
|
guard #available(iOS 26.0, *), let task = longRun as? BGContinuedProcessingTask else { return }
|
|
task.updateTitle(title, subtitle: "Steam Downloader")
|
|
}
|
|
|
|
private func finishLongRun(success: Bool) {
|
|
asked = false
|
|
guard #available(iOS 26.0, *), let task = longRun as? BGContinuedProcessingTask else { return }
|
|
longRun = nil
|
|
task.setTaskCompleted(success: success)
|
|
}
|
|
#endif
|
|
}
|