最近经常会碰到一些问到如何判断手机网络,在这里我简单的介绍几种方法:
一、RealReachability Demo下载
使用Reachability时,如果网络变化,会给出一个通知,但是我们获取的网络状态只有WiFi/WWAN/NotReach几种。我们可以在Reachability返回的通知里,WWAN这种类型下,再做上面的网络判断即可。但是更优的做法就将判断放在Reachability中,在使用的时候直接返回不同的网络状态。
由于最新的Reachability已经支持了IPV6,我也是在最新的Reachability上做了一些改进。
大部分方法跟Reachability一样,我扩展了枚举类型,修改了网络状态判断。
主要修改如下:
typedef NS_ENUM(NSUInteger, HJNetWorkStatus) {
HJNetWorkStatusNotReachable = 0,
HJNetWorkStatusUnknown = 1,
HJNetWorkStatusWWAN2G = 2,
HJNetWorkStatusWWAN3G = 3,
HJNetWorkStatusWWAN4G = 4,
HJNetWorkStatusWiFi = 5,
};
简单的介绍下RealReachability使用
头文件:#import "RealReachability.h"
@property (nonatomic, assign) BOOL isUserReal; // 当前网络是否可用
@property (nonatomic, assign) NSInteger status; // 当前网络状态
//发送通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netWorkChanged:) name:kRealReachabilityChangedNotification object:nil];
- (void)netWorkChanged:(NSNotification *)notification
{
RealReachability *reachability = (RealReachability *)notification.object;
ReachabilityStatus status = [reachability currentReachabilityStatus];
self.isUserReal = YES;
switch (status) {
case RealStatusNotReachable:
self.isUserReal = NO;
self.status = 0;
[self alertMessage:@"没网络"];
break;
case RealStatusViaWiFi:
self.isUserReal = YES;
self.status = 1;
[self alertMessage:@"WIFI"];
break;
case RealStatusViaWWAN:
self.isUserReal = YES;
self.status = 2;
[self alertMessage:@"2G/3G/4G"];
break;
default:
break;
}
}
二、根据状态栏的wifi标志
- (NSString *)getNetWorkStates{
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
NSString *state = [[NSString alloc]init];
int netType = 0;
//获取到网络返回码
for (id child in children) {
if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
//获取到状态栏
netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
switch (netType) {
case 0:
state = @"无网络";
//无网模式
break;
case 1:
state = @"2G";
break;
case 2:
state = @"3G";
break;
case 3:
state = @"4G";
break;
case 5:
{
state = @"wifi";
break;
default:
break;
}
}
}
//根据状态选择
return state;
}
结束语
到这里就结束了,如若不懂的话可以👇留言,也可以加入群讨论
喜欢的话 记得关注、收藏、点赞哟