- 这里使用第三方框架来实现:Reachability
非常简单,但是也是非常实用的 - 懒加载一下
- (Reachability *)reachabilityManager {
if (_reachabilityManager == nil) {
// 根据主机来创建的Reachability
_reachabilityManager = [Reachability reachabilityWithHostName:@"baidu.com"];
}
return _reachabilityManager;
}
使用通知来监听网络状态的改变
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStatusChange) name:kReachabilityChangedNotification object:nil];
// 开始监听
[self.reachabilityManager startNotifier];
}
移除通知
- (void)dealloc {
// 移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
// 停止监听网络状态改变的通知
[self.reachabilityManager stopNotifier];
}
触发
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self networkStatusChange];
}
检测网络状态
- (void)networkStatusChange{
// 获得当前的网络状态
NetworkStatus status = [self.reachabilityManager currentReachabilityStatus];
switch (status) {
case NotReachable:
NSLog(@"没有网络");
break;
case ReachableViaWiFi:
NSLog(@"wifi环境,不用花钱,尽管使用");
break;
case ReachableViaWWAN:
NSLog(@"要花钱,谨慎使用,土豪随意");
break;
}
}