Hi,
I use this code myself in my app:
class NetworkModel {
static let shared = NetworkModel()
private let monitor = NWPathMonitor()
private var connected = true
init() {
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
self.connected = true
} else {
self.connected = false
}
}
let queue = DispatchQueue(label: "Monitor")
monitor.start(queue: queue)
}
/// Retrieves the current network state.
///
/// - Returns: A boolean value indicating the network state (connected or not).
func getNetworkState() -> Bool {
return connected
}
}
Downside is that the very first time it is accessed it is always false. So trigger it during launch so that the monitor can start watching and then it works perfect!
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: