iOS: how to query WiFi state

百般思念 提交于 2019-12-01 21:05:13

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;

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
}

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

[Reachability reachabilityForLocalWiFi];

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