iOS:如何查询WiFi状态 [英] iOS: how to query WiFi state
问题描述
是否可以通过编程方式查询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屋!