38 lines
1.1 KiB
Swift
38 lines
1.1 KiB
Swift
import Foundation
|
|
import Network
|
|
|
|
nonisolated enum NetworkPathStatus: Sendable {
|
|
case available, unavailable, requiresConnection
|
|
}
|
|
|
|
/// OS route status only; no probes and no independent polling timer.
|
|
nonisolated final class NetworkPathObserver: @unchecked Sendable {
|
|
private let monitor = NWPathMonitor()
|
|
private let lock = NSLock()
|
|
private var status: NetworkPathStatus?
|
|
|
|
init() {
|
|
monitor.pathUpdateHandler = { [weak self] path in
|
|
guard let self else { return }
|
|
let next: NetworkPathStatus
|
|
switch path.status {
|
|
case .satisfied: next = .available
|
|
case .requiresConnection: next = .requiresConnection
|
|
default: next = .unavailable
|
|
}
|
|
self.lock.lock()
|
|
self.status = next
|
|
self.lock.unlock()
|
|
}
|
|
monitor.start(queue: DispatchQueue(label: "cn.airnan.kymo.network-path"))
|
|
}
|
|
|
|
func snapshot() -> NetworkPathStatus? {
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
return status
|
|
}
|
|
|
|
deinit { monitor.cancel() }
|
|
}
|