我可以在程序中使用任何系统事件来检测 macOS 上的网络更改吗?如果网络状态发生变化,我想调用一个函数,而不需要在程序中每 x 秒进行一次查找。目前我正在使用“scheduledTimer”进行查找...
有更好的解决方案吗?
NWPathMonitor
API 实现:
/**
* A small program which outputs a line of interfaces (comma separated) on network
* changes. It was the easiest way I could find to watch for network changes on
* macOS without using a polling system.
*
* Compile this with: `swiftc ./net-monitor.swift`
*/
import Foundation
import Network
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
// inspect the `path` variable here for more information
print("\(path)")
}
monitor.start(queue: DispatchQueue(label: "net-monitor"))
dispatchMain()
编译并运行将发出如下所示的行:
satisfied (Path is satisfied), interface: en0[802.11], ipv4, ipv6, dns, uses wifi
satisfied (Path is satisfied), interface: en1, ipv4, ipv6, dns
...
您可以使用
path
对象上的字段来检测当前可用的接口,并检查它们的连接性和功能(以太网与 WiFi 等)。