iOS: how to query WiFi state

◇◆丶佛笑我妖孽 提交于 2019-12-20 02:48:08

问题


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.

EDIT: 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];

回答1:


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

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;



回答2:


You can use Reachability to check this. Import the files, then you can do this:

Reachability *networkReachability = [Reachability  reachabilityWithHostName:@"http://google.com];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == ReachableViaWiFi) {
    //wifi
}



回答3:


You could use the Reachability class that apple has provided here then check for this:

[Reachability reachabilityForLocalWiFi];



来源:https://stackoverflow.com/questions/26206957/ios-how-to-query-wifi-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!