How do I detect captive portals and network changes in Swift?

Swift, captive portal detection, network changes, network reachability, iOS development
This guide explains how to detect captive portals and network changes in Swift, providing practical examples to aid iOS developers in creating robust network-aware applications.

import Network

class NetworkMonitor {
    let monitor = NWPathMonitor()
    var isConnected = false
    var isExpensive = false

    init() {
        monitor.pathUpdateHandler = { path in
            self.isConnected = path.status == .satisfied
            self.isExpensive = path.isExpensive
            
            if self.isConnected {
                print("Network is available")
                if self.isExpensive {
                    print("Network is expensive")
                }
            } else {
                print("No network connection")
            }
        }

        let queue = DispatchQueue(label: "Monitor")
        monitor.start(queue: queue)
    }
}

let networkMonitor = NetworkMonitor()
    

Swift captive portal detection network changes network reachability iOS development