简体   繁体   English

如何以编程方式检查Mac是否已连接到Wi-Fi网络?

[英]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. 我可以使用Reachability检查我的Mac是否已连接到Internet,但我不明白如何专门检查Wi-Fi连接。 Any tips or Swift/Objective-C code are appreciated, thanks in advance. 提前感谢任何提示或Swift / Objective-C代码。

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 CWInterface(name:_)在10.10中已弃用,但仍然有效

Edit Dec 2017: 2017年12月编辑:

A CWWiFiClient based one-line solution for 10.10+: 基于CWWiFiClient单线解决方案:

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

vadian answer without deprecations: vadian回答没有折旧

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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