MOE
MOE

Reputation: 839

macOS system events for network status in Swift

is there any system event which I can use in my program to detect a network change on macOS? I would like to call a function if the network state change, without having a lookup every x seconds in my program. Currently I'm using 'scheduledTimer' to make a lookup...

Is there a better solution for that?

Upvotes: 3

Views: 1509

Answers (1)

This is achievable with the NWPathMonitor API. Using it, we can have a function called each time the state of the network changes (i.e., every time an interface connects or disconnects).

/**
 * A small program which watches for network changes on macOS without using a
 * polling system.
 *
 * Compile this with: `swiftc ./net-monitor.swift`
 */

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()

Compiling and running that will emit lines that look like:

satisfied (Path is satisfied), interface: en0[802.11], ipv4, ipv6, dns, uses wifi
satisfied (Path is satisfied), interface: en1, ipv4, ipv6, dns
...

You can use the fields on the path object to detect the currently available interfaces, and check their connectivity and features (ethernet vs wifi, etc).

Upvotes: 0

Related Questions