问题
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