DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

WonJo
WonJo

Posted on

How To Use NWPathMonitor

import Network

class NetworkMonitor {

    let monitor = NWPathMonitor()

    @Published var connected: Bool = false
    @Published var interfaces: [NWInterface.InterfaceType] = []
    @Published var unsatisfiedReason: NWPath.UnsatisfiedReason?

    func start() {
        monitor.pathUpdateHandler = { [weak self] path in
                        print("Expensive: \(path.isExpensive)") // Cellular or Personal Hotspot
            DispatchQueue.main.async {
                switch path.status {
                case .requiresConnection, .unsatisfied:
                    self?.connected = false
                    self?.unsatisfiedReason = path.unsatisfiedReason
                case .satisfied:
                    self?.connected = true
                @unknown default:
                    break
                }

                self?.interfaces = NWInterface.InterfaceType.allCases.filter({
                    path.usesInterfaceType($0)
                })
            }
        }
        monitor.start(queue: DispatchQueue.global())
    }

    func cancel() {
        monitor.cancel()
    }
}

extension NWInterface.InterfaceType: CaseIterable {
    public static var allCases: [NWInterface.InterfaceType] {
        [.cellular, .loopback, .other, .wifi, .wiredEthernet]
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. 🌈