欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

判断iPhone的WiFi是否打开的两种方法

程序员文章站 2024-02-14 10:39:22
判断wifi是否连接可以使用reachability进行判断,那么wifi是否打开应该怎么判断呢? 下面是两种完全基于不同思路的方法: 方法一: 使用systemc...

判断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。

以上所述是小编给大家介绍的判断iphone的wifi是否打开的两种方法,希望对大家有所帮助