```
-(BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
#pragmamark-监听网络
[self isNetWorking];
returnYES;
}
-(void)isNetWorking{
//开启网络指示器,开始监听
[[AFNetworkReachabilityManagersharedManager]startMonitoring];
// 检测网络连接的单例,网络变化时的回调方法
[[AFNetworkReachabilityManagersharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatusstatus){
}];
}
//========================================
#pragmamark-在需要监听网络的视图控制器实现此方法
-(void)viewDidLoad{
[super viewDidLoad];
[selfAFNetworkStatus];
}
#pragmamark-网络状态判断
-(void)AFNetworkStatus{
//1.创建网络监测者
AFNetworkReachabilityManager*manager=[AFNetworkReachabilityManagersharedManager];
/*枚举里面四个状态 分别对应 未知 无网络 数据 WiFi
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1, 未知
AFNetworkReachabilityStatusNotReachable = 0, 无网络
AFNetworkReachabilityStatusReachableViaWWAN = 1, 蜂窝数据网络
AFNetworkReachabilityStatusReachableViaWiFi = 2, WiFi
};
*/
__weakHome_ViewController*weakSelf=self;
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatusstatus){
//这里是监测到网络改变的block 可以写成switch方便
//在里面可以随便写事件
switch(status){
caseAFNetworkReachabilityStatusUnknown:{
NSLog(@"未知网络状态");
UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:nil message:@"未知网络"delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
[alert show];
weakSelf.NetWorkStatus=NO;
}
break;
caseAFNetworkReachabilityStatusNotReachable:{
NSLog(@"无网络");
UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:nil message:@"无网络"delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
[alert show];
weakSelf.NetWorkStatus=NO;
}
break;
caseAFNetworkReachabilityStatusReachableViaWWAN:{
NSLog(@"蜂窝数据网");
UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:nil message:@"正在使用蜂窝数据网络"delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
[alert show];
weakSelf.NetWorkStatus=YES;
[[NSNotificationCenterdefaultCenter]postNotificationName:@"NetWorkOk"object:nil];
}
break;
caseAFNetworkReachabilityStatusReachableViaWiFi:{
NSLog(@"WiFi网络");
// UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"网络" message:@"WiFi网络" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
// [alert show];
[[NSNotificationCenterdefaultCenter]postNotificationName:@"NetWorkOk"object:nil];
weakSelf.NetWorkStatus=YES;
}
break;
default:
break;
}
}];
}
```