fmodf
b3b3b3aef7
Reviewed-on: narayana/conversations-classic-ios#1 Co-authored-by: fmodf <fmodf.ios@gmail.com> Co-committed-by: fmodf <fmodf.ios@gmail.com>
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
|
|
}
|
|
}
|
|
}
|