简体   繁体   中英

How to programmatically check if Mac is connected to Wi-Fi network?

I'm able to check if my Mac is connected to Internet using Reachability, but I don't understand how to specifically check Wi-Fi connection. Any tips or Swift/Objective-C code are appreciated, thanks in advance.

This code checks if the computer is connected to a wireless network.

It does not check if the wireless network is connected to the internet

import CoreWLAN

func isWIFIActive() -> Bool {
  let interfaceNames = CWInterface.interfaceNames()
  for interfaceName in Array(interfaceNames) {
    let interface = CWInterface(name: interfaceName as! String)
    if interface.ssid() != nil {
      return true
    }
  }
  return false
}


isWIFIActive()

CWInterface(name:_) is deprecated in 10.10 but still works

Edit Dec 2017:

A CWWiFiClient based one-line solution for 10.10+:

func isWIFIActive() -> Bool {
    return CWWiFiClient.interfaceNames()?.contains{ CWWiFiClient.shared().interface(withName: $0)?.ssid() != nil } ?? false
}

vadian answer without deprecations:

func isWIFIActive() -> Bool {
    guard let interfaceNames = CWWiFiClient.interfaceNames() else {
        return false
    }

    for interfaceName in interfaceNames {
        let interface = CWWiFiClient.shared().interface(withName: interfaceName)

        if interface?.ssid() != nil {
            return true
        }
    }
    return false
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM