38 lines
904 B
Swift
38 lines
904 B
Swift
|
import Combine
|
||
|
import Network
|
||
|
|
||
|
extension NWPathMonitor {
|
||
|
func paths() -> AsyncStream<NWPath> {
|
||
|
AsyncStream { continuation in
|
||
|
pathUpdateHandler = { path in
|
||
|
continuation.yield(path)
|
||
|
}
|
||
|
continuation.onTermination = { [weak self] _ in
|
||
|
self?.cancel()
|
||
|
}
|
||
|
start(queue: DispatchQueue(label: "NSPathMonitor.paths"))
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
final actor NetworkMonitor: ObservableObject {
|
||
|
static let shared = NetworkMonitor()
|
||
|
|
||
|
@Published private(set) var isOnline: Bool = false
|
||
|
|
||
|
private let monitor = NWPathMonitor()
|
||
|
|
||
|
init() {
|
||
|
Task(priority: .background) {
|
||
|
await startMonitoring()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func startMonitoring() async {
|
||
|
let monitor = NWPathMonitor()
|
||
|
for await path in monitor.paths() {
|
||
|
isOnline = path.status == .satisfied
|
||
|
}
|
||
|
}
|
||
|
}
|