网络监测 一
首先导入
AFNetworkReachabilityManager.h
#pragma mark -- 检查网络状态
- (void)checkNetworking{
// 1.创建对象
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];// 2.检查网络
//设置网络状态发生改变触发的block
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
/*
AFNetworkReachabilityStatusUnknown = -1, 未知
AFNetworkReachabilityStatusNotReachable = 0, 不可用
AFNetworkReachabilityStatusReachableViaWWAN = 1, 流量
AFNetworkReachabilityStatusReachableViaWiFi = 2, wifi
*/
NSArray *array = @[@"未知错误", @"无网络", @"使用流量", @"wifi环境"];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"网络状态检查” message:array[status + 1] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction*action) {
[alert dismissViewControllerAnimated:YES completion:ni];
}];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
}];
// 开始检查
[manager startMonitoring];
// 停止检查
// [manager stopMonitoring];
}
网络监测 二
https://github.com/tonymillion/Reachability
或者 在终端 git clone https://github.com/tonymillion/Reachability.git
导入
#import "Reachability.h"
#pragma mark 添加网络监控通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
Reachability *reach = [Reachability reachabilityWithHostName:@"公司网址头"];
//例如 www.baidu.com
[reach startNotifier];
#pragma mark 实现网络监控方法
-(void)reachabilityChanged:(NSNotification *)notification
{
Reachability *reach = [notification object];
if([reach isKindOfClass:[Reachability class]]){
NetworkStatus statuWetwork = [reach currentReachabilityStatus];
NSLog(@"statuWetwork %ld",(long)statuWetwork);
switch (statuWetwork) {
case 0:
{
//提示网络不可用
}
break;
default:
break;
}
//Insert your code here
}
}
仅供参考