Home > Software engineering >  Why doesn't path.status report the network connection status correctly in my Swift app?
Why doesn't path.status report the network connection status correctly in my Swift app?

Time:03-23

I have some swift code which uses the Network framework to detect when network connectivity is available or not. If I have wifi turned on and I run my code my code reports that path.status is .satisfied and if I then turn off my wifi my code reports that path.status is .satisfied again. But then if I turn on my wifi again path.status is reported as .unsatisfied then a second later it reports it as .satisfied. What on earth is going on? I would expect path.status to change immediately when wifi is turned off and on and off etc.

Here is my NetworkServices class;

final class NetworkServices {
    
    static let sharedInstance = NetworkServices()
        
    private let queue = DispatchQueue.global(qos: .background)
    
    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 wiredEthernet
        case unknown
    }
    
    private init() {
        monitor = NWPathMonitor()
    }
    
    public func startMonitoring() {
        monitor.start(queue: queue)
        monitor.pathUpdateHandler = { [weak self] path in
            self?.isConnected = path.status == .satisfied
            print("DEBUG: path.status = \(path.status); isConnected = \(self!.isConnected)")
            self?.getConnectionType(path)
        }
    }
    
    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 = .wiredEthernet
        } else {
            connectionType = .unknown
        }
    }
}

I call the startMonitoring method in my AppDelegate file's didFinishLaunchingWithOptions method

CodePudding user response:

As you turn on wifi, It notify for NWPath update but until then connection has not been established, it takes some moment to connect.

CodePudding user response:

The pathUpdateHandler does not work properly in an iOS simulator but works as expected on a real device.

  • Related