Get the network interface type on button click without continuously monitoring swift iOS


You can use async/await so you can cancel once you have a result.

/// Queries `NWPathMonitor` for the `usesInterfaceType`.
/// Supported types are `NWInterface.InterfaceType.other, .cellular, .wifi, .wiredEthernet, .loopback`
/// - Returns: `String` value of the interface type, if known or an "Empty String`.`
static func connectiontype() async -> String{
    typealias Continuation = CheckedContinuation<String, Never>
    return await withCheckedContinuation({ (continuation: Continuation) in
        let monitor = NWPathMonitor()

        monitor.pathUpdateHandler = { path in
            var result = ""
            for item in [NWInterface.InterfaceType.other, .cellular, .wifi, .wiredEthernet, .loopback] {
                if path.usesInterfaceType(item){
                    result = "\(item)"
                    break
                }
            }
            monitor.cancel()
            continuation.resume(returning: result)
        }
        monitor.start(queue: DispatchQueue(label: "InternetConnectionMonitor"))
    })
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img