Swift 中网络状态的 macOS 系统事件

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

我可以在程序中使用任何系统事件来检测 macOS 上的网络更改吗?如果网络状态发生变化,我想调用一个函数,而不需要在程序中每 x 秒进行一次查找。目前我正在使用“scheduledTimer”进行查找...

有更好的解决方案吗?

swift macos cocoa network-programming systemevent
1个回答
0
投票

这可以通过

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 等)。

© www.soinside.com 2019 - 2024. All rights reserved.