在项目中经常需要考虑到网络断开的情况,有时候还需要实时监测网络状态,Reachability是苹果官方推荐的方法,要求iOS8以上系统,参考地址: https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html
简单介绍下如何使用
1、初始化
//添加监听网络状态
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
Reachability *netReach = [Reachability reachabilityWithHostName:@"www.baidu.com"]; //最好声明在成员里面
[netReach startNotifier];
2、添加响应方法:
- (void)reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
if ([curReach isKindOfClass:[Reachability class]]) {
NetworkStatus netStatus = [curReach currentReachabilityStatus];
if (netStatus != NotReachable) {
NSLog(@"有网络连接");
}else
{
NSLog(@"无网络连接");
}
}
}
最后别忘了释放注册消息
[[NSNotificationCenter defaultCenter] removeObserver:kReachabilityChangedNotification];