summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Operations/BackgroundObserver.swift
blob: e5d83c62350f08706617f68833f9d4232728f16e (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
//
//  BackgroundObserver.swift
//  MullvadVPN
//
//  Created by pronebird on 31/05/2022.
//

#if canImport(UIKit)

import UIKit

class BackgroundObserver: OperationObserver {
    let name: String
    let application: UIApplication
    let cancelUponExpiration: Bool

    private var taskIdentifier: UIBackgroundTaskIdentifier?

    init(
        application: UIApplication = .shared,
        name: String,
        cancelUponExpiration: Bool
    )
    {
        self.application = application
        self.name = name
        self.cancelUponExpiration = cancelUponExpiration
    }

    func didAttach(to operation: Operation) {
        let expirationHandler = cancelUponExpiration ? { operation.cancel() } : nil

        taskIdentifier = application.beginBackgroundTask(
            withName: name,
            expirationHandler: expirationHandler
        )
    }

    func operationDidStart(_ operation: Operation) {
        // no-op
    }

    func operationDidCancel(_ operation: Operation) {
        // no-op
    }

    func operationDidFinish(_ operation: Operation) {
        if let taskIdentifier = taskIdentifier {
            application.endBackgroundTask(taskIdentifier)
        }
    }
}

#endif