本文共 2690 字,大约阅读时间需要 8 分钟。
1.AFNNetworking
//AFN判断网络
-(void)getInternetStatue{
// 1.获得网络监控的管理者
AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
// 2.设置网络状态改变后的处理
[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
// 当网络状态改变了, 就会调用这个block
switch (status) {
case AFNetworkReachabilityStatusUnknown: // 未知网络
NSLog(@"未知网络");
break;
case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
NSLog(@"没有网络(断网)");
break;
case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
NSLog(@"手机自带网络");
break;
case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
NSLog(@"WIFI");
break;
}
if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
{
// NSLog(@"有网");
}else
{
NSLog(@"没有网");
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"网络失去连接" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
alert.delegate = self;
[alert show];
}
}];
// 3.开始监控
[mgr startMonitoring];
}
2.Reachability
需要把该工程中的Reachability.h 和 Reachability.m 拷贝到你的工程中,同时需要把 SystemConfiguration.framework 添加到工程中,
// 监听网络状态改变的通知[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];// 创建Reachabilityself.conn = [Reachability reachabilityForInternetConnection];// 开始监控网络(一旦网络状态发生改变, 就会发出通知kReachabilityChangedNotification)[self.conn startNotifier];// 处理网络状态改变- (void)networkStateChange{ // 1.检测wifi状态 Reachability *wifi = [Reachability reachabilityForLocalWiFi]; // 2.检测手机是否能上网络(WIFI\3G\2.5G) Reachability *conn = [Reachability reachabilityForInternetConnection]; // 3.判断网络状态 if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi NSLog(@"有wifi"); } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网 NSLog(@"使用手机自带网络进行上网"); } else { // 没有网络 NSLog(@"没有网络"); }}3.从状态中获取网络
//从状态栏中获取网络类型,代码如下:
- (NSString *)getNetWorkStates{
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
NSLog(@"---%@---",children);
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;
}
转载地址:http://uzmgi.baihongyu.com/