检测wifi是否开启

Detect if wifi is turned on

有没有办法检测 iPhone/iPad 上是否启用了 wifi?

我对是否可以访问 Internet 不感兴趣,因为我使用可达性 class。我只需要知道设备上是否启用了wifi。

感谢任何提示。

有几个问题涉及同一主题。你试过了吗this code from Apple

@property (retain, nonatomic)  Reachability* reach;

self.reach = [Reachability reachabilityForInternetConnection]; //retain reach
[self.reach startNotifier];

NetworkStatus remoteHostStatus = [self.reach currentReachabilityStatus];

if(remoteHostStatus == NotReachable) {NSLog(@"init **** Not Reachable ****");}
else if (remoteHostStatus == ReachableViaWiFi) {NSLog(@"int **** wifi ****"); }
else if (remoteHostStatus == ReachableViaWWAN) {NSLog(@"init **** cell ****"); }

有一个project on github.。导入到您的项目中,您可以像这样检查连接:

Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];

NetworkStatus status = [reachability currentReachabilityStatus];

if(status == NotReachable) 
{
    //No internet
}
else if (status == ReachableViaWiFi)
{
    //WiFi
}
else if (status == ReachableViaWWAN) 
{
    //3G
}

The code from here.

也许这就是您要找的:

DEAD LINK: http://www.enigmaticape.com/blog/determine-wifi-enabled-ios-one-weird-trick

Wayback Machine Archive: https://web.archive.org/web/20161114213529/http://www.enigmaticape.com/blog/determine-wifi-enabled-ios-one-weird-trick

对于您想要做的事情,没有一个框架,但有一个技巧可能会奏效。如果列出可用的接口,就会有一些接口是在打开wifi时才出现的(还有一些是在你连接时才出现的。你可以这样列出接口:

struct ifaddrs *interfaces;
 
if(!getifaddrs(&interfaces)) {
    for( struct ifaddrs *interface = interfaces; interface; interface=interface->ifa_next) {
        BOOL up = (interface->ifa_flags & IFF_UP) == IFF_UP;
        if ( up ) {
            NSLog(
                @"Name : %s, sa_family : %d",
                interface->ifa_name,
                interface->ifa_addr->sa_family
            );
        }
    }
}

Wifi 关闭时的输出:

Name : lo0, sa_family : 18
Name : lo0, sa_family : 30
Name : lo0, sa_family : 2
Name : lo0, sa_family : 30
Name : pdp_ip0, sa_family : 18
Name : pdp_ip0, sa_family : 2
Name : en0, sa_family : 18
Name : awdl0, sa_family : 18

打开 wifi 时输出:

Name : lo0, sa_family : 18
Name : lo0, sa_family : 30
Name : lo0, sa_family : 2
Name : lo0, sa_family : 30
Name : pdp_ip0, sa_family : 18
Name : pdp_ip0, sa_family : 2
Name : en0, sa_family : 18
Name : awdl0, sa_family : 18
Name : awdl0, sa_family : 30

打开并连接 wifi 的输出:

Name : lo0, sa_family : 18
Name : lo0, sa_family : 30
Name : lo0, sa_family : 2
Name : lo0, sa_family : 30
Name : pdp_ip0, sa_family : 18
Name : pdp_ip0, sa_family : 2
Name : en0, sa_family : 18
Name : en0, sa_family : 30
Name : en0, sa_family : 2
Name : awdl0, sa_family : 18
Name : awdl0, sa_family : 30

如果您探索 ifaddrs 结构,您还会发现已连接网络的 BSSID/SSID。