Taras Parkhomenko
Taras Parkhomenko

Reputation: 41

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.

Upvotes: 1

Views: 1930

Answers (2)

vadian
vadian

Reputation: 285069

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 CWWiFiClientbased one-line solution for 10.10+:

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

Upvotes: 3

AVerguno
AVerguno

Reputation: 1377

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
}

Upvotes: 0

Related Questions