In order to detect if there is a network connection, I have created a class:
import Foundation
import Network
final class NetworkMonitor: ObservableObject {
static let shared = NetworkMonitor()
private let queue = DispatchQueue(label: "Network") // DispatchQueue.global()
private let monitor: NWPathMonitor
public private(set) var isConnected: Bool = false
public private(set) var connectionType: ConnectionType = .unknown
enum ConnectionType {
case wifi
case cellular
case ethernet
case unknown
}
private init() {
monitor = NWPathMonitor()
}
public func startMonitoring() {
monitor.start(queue: queue)
monitor.pathUpdateHandler = { [weak self] path in
self?.isConnected = path.status == .satisfied
self?.getConnectionType(path)
DispatchQueue.main.async {
self?.objectWillChange.send()
}
}
print("@@34355 Etat de la connexion: \(self.isConnected)")
}
public func stopMonitoring() {
monitor.cancel()
}
private func getConnectionType(_ path: NWPath) {
if path.usesInterfaceType(.wifi) {
connectionType = .wifi
} else if path.usesInterfaceType(.cellular) {
connectionType = .cellular
} else if path.usesInterfaceType(.wiredEthernet) {
connectionType = .ethernet
} else {
connectionType = .unknown
}
}
}
I use it like this everywhere in my code in some func after viewDidAppear:
if NetworkMonitor.shared.isConnected == true {
// Do something
}
And I put this in the appDelegate:
NetworkMonitor.shared.startMonitoring()
The connection is detected correctly the first time, but if it changes, the isConnected doesn't work well. he displays the opposite: When i active the wifi for the simulator, the isConnected is on false, and when i shut it down, he is on true. I already tried to work with .unsatisfied. but with no success
How could I fix it?