diff options
| author | Andrej Mihajlov <and@mullvad.net> | 2022-09-25 16:34:23 +0200 |
|---|---|---|
| committer | Andrej Mihajlov <and@mullvad.net> | 2022-09-26 16:35:38 +0200 |
| commit | f389956c2cd884df142adbf00ff2ac7e2f69c2b2 (patch) | |
| tree | 5f7d4869324760eb4ba0107c0356edc89efd1457 /ios/Operations/BackgroundObserver.swift | |
| parent | 2e83b1ca27ff243a615ff10c94c20840b38dfd45 (diff) | |
| download | mullvadvpn-f389956c2cd884df142adbf00ff2ac7e2f69c2b2.tar.xz mullvadvpn-f389956c2cd884df142adbf00ff2ac7e2f69c2b2.zip | |
Move AsyncOperation into Operations static library and add separate tests
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 |
