0

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?

Christine
  • 31
  • 6
  • There is a callback method, pathUpdateHandler, that you need to implement and where you can react changes. – Joakim Danielson Nov 15 '22 at 11:06
  • @JoakimDanielson thank you, but if you read my post, you will see that i have already implemented it. Perhaps it's a simulator problem, of a bug in xcode 13.2 – Christine Nov 15 '22 at 18:20
  • Sorry, how could I have missed that. According to another [question](https://stackoverflow.com/questions/63617783/why-does-nwpathmonitor-not-give-a-path-update-when-the-path-becomes-satisfied) I found this class is not reliable in the simulator and needs to be tested on a real device – Joakim Danielson Nov 15 '22 at 18:28
  • Does theis import Network has an Error, for example i wanna present an error specific to that connection is not available – Mahmoud Zinji Mar 23 '23 at 12:16

0 Answers0