summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Promise/Promise+BackgroundTask.swift
blob: 95561717a81ef2d874c539e16effcdef15bdb817 (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
//
//  Promise+BackgroundTask.swift
//  Promise+BackgroundTask
//
//  Created by pronebird on 06/09/2021.
//  Copyright © 2021 Mullvad VPN AB. All rights reserved.
//

import UIKit

extension Promise {

    /// Start the background task for the duration of the upstream execution.
    func requestBackgroundTime(taskName: String? = nil) -> Promise<Value> {
        return Promise<Value>(parent: self) { resolver in
            var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

            let beginBackgroundTask = {
                backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: taskName) {
                    resolver.resolve(completion: .cancelled)
                }
            }

            let endBackgroundTask = {
                guard let taskIdentifier = backgroundTaskIdentifier,
                      taskIdentifier != .invalid else { return }

                UIApplication.shared.endBackgroundTask(taskIdentifier)
                backgroundTaskIdentifier = nil
            }

            if Thread.isMainThread {
                beginBackgroundTask()
            } else {
                DispatchQueue.main.async(execute: beginBackgroundTask)
            }

            self.observe { completion in
                resolver.resolve(completion: completion)

                if Thread.isMainThread {
                    endBackgroundTask()
                } else {
                    DispatchQueue.main.async(execute: endBackgroundTask)
                }
            }
        }
    }
}