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

Latest comments (0)