简介
在开发的过程中,常常需要对当前的网络状态进行检测,通常我们尝借助一些第三方框架,例如AFNetworking中检测网络是否连接的方法来进行网络检测,但是其弊端就是当网络状态发生改变的时候,不可能实时的知道网络状态发生改变,必须通过调用相应的方法才可以知道,在网络上查找了一些方法后,才知道原来苹果提供了相应的实时检测网络的类Reachability,苹果的官方框架,只不过没有集成到xcode里面去,可到苹果官方网站上面去下载下载地址,只需要导入调用即可.
使用
使用过程中,只需添加头文件"Reachability.h",导入框架SystemConfiguration.framework,使用方法如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window =[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.window.backgroundColor=[UIColor whiteColor];
KKLoginViewController *login = [[KKLoginViewController alloc] init];
self.window.rootViewController = login;
[self.window makeKeyAndVisible];
//实时检测网络的方法
[self checkNetWorkOntime];
[self setCrshLog];
//[self checkVersion];
return YES;
}
//实时监听网络状态
-(void)checkNetWorkOntime {
//创建网络监听
[AppDelegate getInstance].netStatus=1;//默认网络好的
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
//创建网络监听对象
self.reachability = [Reachability reachabilityForInternetConnection];
//开始检测
[self.reachability startNotifier];
[AppDelegate getInstance].netStatus=[self.reachability currentReachabilityStatus];
}
//网络状态结果变化后的处理
- (void)reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
NetworkStatus status = [curReach currentReachabilityStatus];
[AppDelegate getInstance].netStatus=status;
[[NSNotificationCenter defaultCenter]postNotificationName:NetWorkChangeNotification object:nil userInfo:@{@"status":@(status)}];
}