diff options
Diffstat (limited to 'ios/Operations/BackgroundObserver.swift')
| -rw-r--r-- | ios/Operations/BackgroundObserver.swift | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/ios/Operations/BackgroundObserver.swift b/ios/Operations/BackgroundObserver.swift new file mode 100644 index 0000000000..1de842f766 --- /dev/null +++ b/ios/Operations/BackgroundObserver.swift @@ -0,0 +1,54 @@ +// +// BackgroundObserver.swift +// MullvadVPN +// +// Created by pronebird on 31/05/2022. +// Copyright © 2022 Mullvad VPN AB. All rights reserved. +// + +#if canImport(UIKit) + +import UIKit + +public final class BackgroundObserver: OperationObserver { + public let name: String + public let application: UIApplication + public let cancelUponExpiration: Bool + + private var taskIdentifier: UIBackgroundTaskIdentifier? + + public init( + application: UIApplication = .shared, + name: String, + cancelUponExpiration: Bool + ) { + self.application = application + self.name = name + self.cancelUponExpiration = cancelUponExpiration + } + + public func didAttach(to operation: Operation) { + let expirationHandler = cancelUponExpiration ? { operation.cancel() } : nil + + taskIdentifier = application.beginBackgroundTask( + withName: name, + expirationHandler: expirationHandler + ) + } + + public func operationDidStart(_ operation: Operation) { + // no-op + } + + public func operationDidCancel(_ operation: Operation) { + // no-op + } + + public func operationDidFinish(_ operation: Operation, error: Error?) { + if let taskIdentifier = taskIdentifier { + application.endBackgroundTask(taskIdentifier) + } + } +} + +#endif |
