判斷iPhone的WiFi是否開啟的兩種方法 之是否串連上 WiFi,iphonewifi
iOS中用來查詢當前串連的網路資訊的API即CNCopyCurrentNetworkInfo
這個API位於SystemConfiguration.framework裡面,使用時需要增加.h和包含庫檔案
使用時可以直接包含
#import <SystemConfiguration/CaptiveNetwork.h>
代碼如下:
+ (NSString *)getWifiName
{
NSString *wifiName = nil;
CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
if (!wifiInterfaces) {
return nil;
}
NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
for (NSString *interfaceName in interfaces) {
CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
if (dictRef) {
NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
NSLog(@"network info -> %@", networkInfo);
wifiName = [networkInfo objectForKey:(__bridge NSString*)kCNNetworkInfoKeySSID];
CFRelease(dictRef);
}
}
CFRelease(wifiInterfaces);
return wifiName;
}
判斷WiFi是否串連可以使用Reachability進行判斷,那麼WiFi是否開啟應該怎麼判斷呢?
下面是兩種完全基於不同思路的方法:
方法一:
使用SystemConfiguration.framework
庫進行判斷
#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;}
方法二:
使用KVC對StatusBar進行判斷
- (BOOL)isWiFiConnected { UIApplication *app = [UIApplication sharedApplication]; NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews]; //獲得到網路返回碼 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 分別對應的網路狀態是2G、3G、4G及WIFI。(需要判斷當前網路類型寫個switch 判斷就OK) } } NSLog(@"not open network or no net work"); return NO;}
實際上,方法二也是對網路連接狀態的判斷,不能判斷WiFi是否開啟。不同的網路連接狀態下,StatusBar展示不同的表徵圖,當WiFi開啟而沒串連時,方法二得到的結果依然會是NO。
原文連結:http://blog.csdn.net/smking/article/details/38895275