在我的应用程序中,需要在按钮操作上查找互联网连接类型(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()
}
我不需要持续监控连接类型的变化。我只需要在调用网络服务时检查类型。对于这种情况,还有其他可遵循的吗?
您可以使用
async/await
,以便在获得结果后可以 cancel
。
/// 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"))
})
}