iOS:如何查询WiFi状态 [英] iOS: how to query WiFi state

查看:361
本文介绍了iOS:如何查询WiFi状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过编程方式查询iOS上的WiFi状态(启用/禁用)?当启用WiFi并且设备未连接到任何网络时,查询应返回true。

Is it possible to query WiFi state (enabled/disabled) on iOS programmatically? The query should return true when WiFi is enabled and device is not connected to any network.

编辑:我知道提供的功能可达性类,据我所知,它无法识别已启用但未连接的WIFI状态。即以下代码将返回 NetworkStatus NotReachable ,这不是我需要的。

I am aware of the functionality provided by Reachability class and as far as I understand it does not recognize enabled but not connected state of WIFI. I.e. the following code will return NetworkStatus NotReachable, which is not what I need.

Reachability* r = [Reachability reachabilityForLocalWiFi];
NetworkStatus ns = [r currentReachabilityStatus];


推荐答案

免责声明:以下解决方案不健全并且无法保证它会通过AppStore

Disclaimer: The following solution is not robust and there is no guarantee it will pass AppStore.

我能找到的唯一可行的解​​决方案是请求并使用 getifaddrs 函数评估可用接口列表。如果WiFi禁用/启用/连接,列表看起来会有所不同:

The only viable solution I was able to find so far is to request and evaluate a list of available interfaces using getifaddrs function. The list looks differently in case WiFi disabled/enabled/connected:

NSCountedSet * cset = [NSCountedSet new];
struct ifaddrs *interfaces;

if( ! getifaddrs(&interfaces) ) {
    for( struct ifaddrs *interface = interfaces; interface; interface = interface->ifa_next) {
        if ( (interface->ifa_flags & IFF_UP) == IFF_UP ) {
            [cset addObject:[NSString stringWithUTF8String:interface->ifa_name]];
        }
    }
}

freeifaddrs(interfaces);

return [cset countForObject:@"awdl0"] > 1 ? WIFI_ON : WIFI_OFF;

这篇关于iOS:如何查询WiFi状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆