Two methods to judge whether WiFi of iPhone is turned on or not

  • 2021-07-18 09:08:16
  • OfStack

Whether WiFi is connected can be judged by Reachability, so how should WiFi be turned on?

Here are two approaches based entirely on different ideas:

Method 1:

Use the SystemConfiguration. framework library for judgment


#import <ifaddrs.h>
#import <net/if.h>
#import <SystemConfiguration/CaptiveNetwork.h>
- (BOOL) isWiFiEnabled {
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]];
}
}
}
return [cset countForObject:@"awdl0"] > 1 ? YES : NO;
}

Method 2:

Judgment of StatusBar using KVC


- (BOOL)isWiFiConnected {
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
// Get the return code to the network 
for (id child in children) {
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
int netType = [[child valueForKeyPath:@"dataNetworkType"] intValue];
NSLog(@"type:%@",@(netType));
if (netType == 1) {
NSLog(@"2G");
return NO;
}
else if (netType == 2) {
NSLog(@"3G");
return NO;
}
else if (netType == 3) {
NSLog(@"4G");
return NO;
}
else if (netType == 5){
NSLog(@"Wifi");
return YES;
}
// 1 , 2 , 3 , 5  The corresponding network states are 2G , 3G , 4G And WIFI . ( Need to judge the current network type and write a switch  Judge on OK)
}
}
NSLog(@"not open network or no net work");
return NO;
}

In fact, method 2 also judges the network connection status, and cannot judge whether WiFi is turned on or not. Under different network connection states, StatusBar displays different icons. When WiFi is turned on but not connected, the result obtained by method 2 will still be NO.


Related articles: