summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Operations/PresentAlertOperation.swift
blob: 7dff3399f6c2a807bd55f13dca1108b9bc35e282 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
//  PresentAlertOperation.swift
//  MullvadVPN
//
//  Created by pronebird on 06/09/2021.
//  Copyright © 2021 Mullvad VPN AB. All rights reserved.
//

import Operations
import UIKit

final class PresentAlertOperation: AsyncOperation {
    private let alertController: CustomAlertViewController
    private let presentingController: UIViewController
    private let presentCompletion: (() -> Void)?

    init(
        alertController: CustomAlertViewController,
        presentingController: UIViewController,
        presentCompletion: (() -> Void)? = nil
    ) {
        self.alertController = alertController
        self.presentingController = presentingController
        self.presentCompletion = presentCompletion

        super.init(dispatchQueue: .main)
    }

    override 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 func main() {
        alertController.didDismiss = { [weak self] in
            self?.finish()
        }

        presentingController.present(alertController, animated: true) {
            self.presentCompletion?()

            // Alert operation was cancelled during transition?
            if self.isCancelled {
                self.dismissAndFinish()
            }
        }
    }

    private func dismissAndFinish() {
        alertController.dismiss(animated: false) {
            self.finish()
        }
    }
}