此篇文章將要引見判別iPhone的WiFi能否翻開的兩種辦法 之能否銜接上 WiFi的相關引見,詳細實例請看下文
IOS中用來查詢以後銜接的網絡信息的API即CNCopyCurren.networkInfo
這個API位於SystemConfiguration.framework外面,運用時需求添加.h和包括庫文件
運用時可以直接包括
#import<SystemConfiguration/Captiv.network.h>
代碼如下:
+ (NSString*)getWifiName
{
NSString*wifiName =nil;
CFArrayRefwifiInterfaces =CNCopySupportedInterfaces();
if(!wifiInterfaces) {
returnnil;
}
NSArray*interfaces = (__bridgeNSArray*)wifiInterfaces;
for(NSString*interfaceNameininterfaces) {
CFDictionaryRefdictRef =CNCopyCurren.networkInfo((__bridgeCFStringRef)(interfaceName));
if(dictRef) {
NSDictionary*networkInfo = (__bridgeNSDictionary*)dictRef;
NSLog(@"network info -> %@", networkInfo);
wifiName = [networkInfoobjectForKey:(__bridgeNSString*)kCNNetworkInfoKeySSID];
CFRelease(dictRef);
}
}
CFRelease(wifiInterfaces);
returnwifiName;
}
判別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多多關注本站,我們將為您搜集更多的Android開發相關文章.
【判別iPhone的WiFi能否翻開的兩種辦法 之能否銜接上 WiFi】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!