iOS: how to query WiFi state
Asked Answered
H

3

3

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];
Haith answered 5/10, 2014 at 20:35 Comment(3)
Use Reachability. The Apple sample code describes basic use cases for monitoring different types of network connections. developer.apple.com/library/IOs/samplecode/Reachability/…Thermosetting
If I'm understanding your edits correctly, there isn't a way to query whether WiFi is explicitly enabled or disabled by the user. Reachability will answer whether a network is "reachable" via a specific method (ie. Wifi), but there's no way to query whether a user has actually turned their WiFi antenna off, for example.Thermosetting
@ChrisDroukas: Yes, this is exactly the case.Haith
H
4

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;
Haith answered 7/10, 2014 at 14:51 Comment(1)
If believe that the awdl0 interface is the Wi-Fi Direct interface, so this checks for Wi-Fi Direct availability? It shouldn't work in iPhone 4, for instance. Can anybody confirm?Sisson
Y
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
}
Yumuk answered 5/10, 2014 at 20:58 Comment(0)
O
2

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

[Reachability reachabilityForLocalWiFi];

Otto answered 5/10, 2014 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.