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/PresentAlertOperation.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/PresentAlertOperation.swift')
| -rw-r--r-- | ios/Operations/PresentAlertOperation.swift | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/ios/Operations/PresentAlertOperation.swift b/ios/Operations/PresentAlertOperation.swift new file mode 100644 index 0000000000..f9fae07e0c --- /dev/null +++ b/ios/Operations/PresentAlertOperation.swift @@ -0,0 +1,75 @@ +// +// PresentAlertOperation.swift +// PresentAlertOperation +// +// Created by pronebird on 06/09/2021. +// Copyright © 2021 Mullvad VPN AB. All rights reserved. +// + +#if canImport(UIKit) + +import UIKit + +public final class PresentAlertOperation: AsyncOperation { + private let alertController: UIAlertController + private let presentingController: UIViewController + private let presentCompletion: (() -> Void)? + + public init( + alertController: UIAlertController, + presentingController: UIViewController, + presentCompletion: (() -> Void)? = nil + ) { + self.alertController = alertController + self.presentingController = presentingController + self.presentCompletion = presentCompletion + + super.init(dispatchQueue: .main) + } + + override public func operationDidCancel() { + // Guard against trying to dismiss the alert when operation hasn't started yet. + guard isExecuting else { return } + + // Guard against dismissing controller during transition. + if !alertController.isBeingPresented, !alertController.isBeingDismissed { + dismissAndFinish() + } + } + + override public func main() { + NotificationCenter.default.addObserver( + self, + selector: #selector(alertControllerDidDismiss(_:)), + name: AlertPresenter.alertControllerDidDismissNotification, + object: alertController + ) + + presentingController.present(alertController, animated: true) { + self.presentCompletion?() + + // Alert operation was cancelled during transition? + if self.isCancelled { + self.dismissAndFinish() + } + } + } + + private func dismissAndFinish() { + NotificationCenter.default.removeObserver( + self, + name: AlertPresenter.alertControllerDidDismissNotification, + object: alertController + ) + + alertController.dismiss(animated: false) { + self.finish() + } + } + + @objc private func alertControllerDidDismiss(_ note: Notification) { + finish() + } +} + +#endif |
