iOS 实时监听网络变化
2017-12-28 本文已影响0人
afstand距离
最近项目中遇到了要判断用户是以哪种上网方式,再做不同的操作,每次主动读取网络状态重复代码太多,因此找到了两种监听网络被动响应的方法。
AFNetworkReachabilityManager
- 添加框架
pod 'AFNetworking', '~> 2.6.3'
- 导入头文件
#import "AFNetworking.h"
- 监听网络
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self listenNetWorkingStatus]; //监听网络是否可用
}
-(void)listenNetWorkingStatus{
//1:创建网络监听者
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager manager];
//2:获取网络状态
/*
AFNetworkReachabilityStatusUnknown = 未知网络,
AFNetworkReachabilityStatusNotReachable = 没有联网
AFNetworkReachabilityStatusReachableViaWWAN = 蜂窝数据
AFNetworkReachabilityStatusReachableViaWiFi = 无线网
*/
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
NSLog(@"未知网络");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"没有联网");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"蜂窝数据");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"无线网");
break;
default:
break;
}
}];
//开启网络监听
[manager startMonitoring];
}
RealReachability
- 添加框架
pod 'RealReachability', '~> 1.1.2'
- 导入头文件
#import "RealReachability.h"
- 监听网络
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self listenNetWorkingStatus]; //监听网络是否可用
}
-(void)listenNetWorkingStatus{
[GLobalRealReachability startNotifier];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(networkChanged:)
name:kRealReachabilityChangedNotification
object:nil];
ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
[self realNetworkingStatus:status];
}
- (void)networkChanged:(NSNotification *)notification
{
RealReachability *reachability = (RealReachability *)notification.object;
ReachabilityStatus status = [reachability currentReachabilityStatus];
[self realNetworkingStatus:status];
}
-(void)realNetworkingStatus:(ReachabilityStatus)status{
switch (status)
{
case RealStatusUnknown:
{
NSLog(@"~~~~~~~~~~~~~RealStatusUnknown");
break;
}
case RealStatusNotReachable:
{
NSLog(@"~~~~~~~~~~~~~RealStatusNotReachable");
break;
}
case RealStatusViaWWAN:
{
NSLog(@"~~~~~~~~~~~~~RealStatusViaWWAN");
break;
}
case RealStatusViaWiFi:
{
NSLog(@"~~~~~~~~~~~~~RealStatusViaWiFi");
break;
}
default:
break;
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}