p2p-swift / Sources / IrdP2P / Lifecycle / AppLifecycleObserver.swift
121 words
 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
import Foundation
#if canImport(UIKit) && !os(watchOS)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif

/// Calls `onForeground` when the app returns to the foreground (iOS) or becomes
/// active (macOS), so rooms can reconnect immediately instead of waiting out a backoff.
final class AppLifecycleObserver: Sendable {
    private let task: Task<Void, Never>?

    init(onForeground: @escaping @Sendable () async -> Void) {
        #if canImport(UIKit) && !os(watchOS)
        let name = UIApplication.willEnterForegroundNotification
        #elseif canImport(AppKit)
        let name = NSApplication.didBecomeActiveNotification
        #else
        let name: Notification.Name? = nil
        #endif
        if let name = name as Notification.Name? {
            task = Task {
                for await _ in NotificationCenter.default.notifications(named: name) {
                    if Task.isCancelled { return }
                    await onForeground()
                }
            }
        } else {
            task = nil
        }
    }

    func cancel() { task?.cancel() }
}

static mirror of HEAD · about · clone: git clone https://ird.cod-sursa.ro/p2p-swift.git