在按钮单击时获取网络接口类型,无需持续监控 swift iOS

问题描述 投票:0回答:1

在我的应用程序中,需要在按钮操作上查找互联网连接类型(wifi/移动数据/等),并将该类型与 Web 服务请求一起发送。 我偶然发现了苹果网络框架并尝试了网络监视器功能

func checkForInternetConnection(){
        var connectionType = ""
        let queue = DispatchQueue(label: "NetworkMonitor")
        let pathMonitor = NWPathMonitor()
        pathMonitor.pathUpdateHandler = {
            path in
            
            if path.usesInterfaceType(.wifi){
                connectionType = "wifi"
            }else if path.usesInterfaceType(.cellular){
                connectionType = "cellular"
            }else{
                connectionType = "other"
            }
        }
        pathMonitor.start(queue: queue)
        pathMonitor.cancel()
    }

我不需要持续监控连接类型的变化。我只需要在调用网络服务时检查类型。对于这种情况,还有其他可遵循的吗?

ios swift networking connection swift5
1个回答
0
投票

您可以使用

async/await
,以便在获得结果后可以
cancel

static func connectiontype() async -> String{
    typealias Continuation = CheckedContinuation<String, Never>
    return await withCheckedContinuation({ (continuation: Continuation) in
        let monitor = NWPathMonitor()

        monitor.pathUpdateHandler = { path in                
            for item in [NWInterface.InterfaceType.wifi, .cellular, .loopback, .wiredEthernet, .other] {
                if path.usesInterfaceType(item){
                    monitor.cancel()
                    continuation.resume(returning: "\(item)" )
                }
            }
        }
        monitor.start(queue: DispatchQueue(label: "InternetConnectionMonitor"))
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.