1.第一种效果
在文件中加入Reachability,MBProgressHUD库
在xxxxx.m中,加入头文件
#import"Reachability.h"
#import"MBProgressHUD.h"
在需要判断的地方,加上[selfisConnectionAvailable];
-(BOOL)isConnectionAvailable{
BOOLisExistenceNetwork=YES;
Reachability*reach=[ReachabilityreachabilityWithHostName:@"www.apple.com"];
switch([reachcurrentReachabilityStatus]){
caseNotReachable:
isExistenceNetwork=NO;
//NSLog(@"notReachable");
break;
caseReachableViaWiFi:
isExistenceNetwork=YES;
//NSLog(@"WIFI");
break;
caseReachableViaWWAN:
isExistenceNetwork=YES;
//NSLog(@"3G");
break;
}
if(!isExistenceNetwork){
MBProgressHUD*hud=[MBProgressHUDshowHUDAddedTo:self.viewanimated:YES];//<spanstyle="font-family:Arial,Helvetica,sans-serif;">MBProgressHUD为第三方库,不需要可以省略或使用AlertView</span>
hud.removeFromSuperViewOnHide=YES;
hud.mode=MBProgressHUDModeText;
hud.labelText=@"网络状态不佳,请检查网络";
hud.minSize=CGSizeMake(132.f,
60.0f);
[hudhide:YESafterDelay:3];
returnNO;
}
returnisExistenceNetwork;
}
//效果如图:
2.第二种效果
在项目中加入AFNetworking 、TSMessage 、HexColor库
在xxxx.m中引入头文件
#import"AFNetworking.h"
#import"TSMessage.h"
在监测网络的地方
//检查网络状态
[selfcheckNetworkStatus];
#pragmamark网络状态监测
-(void)checkNetworkStatus{
//tsmessage
//[TSMessagesetDefaultViewController:self.view];
//创建一个用于测试的url
NSURL*url=[NSURLURLWithString:@"http://www.apple.com"];
AFHTTPRequestOperationManager*operationManager=[[AFHTTPRequestOperationManageralloc]initWithBaseURL:url];
//根据不同的网络状态改变去做相应处理
[operationManager.reachabilityManagersetReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatusstatus){
switch(status){
caseAFNetworkReachabilityStatusReachableViaWWAN:
[TSMessageshowNotificationWithTitle:@"2G/3G/4G连接."type:TSMessageNotificationTypeWarning];
break;
caseAFNetworkReachabilityStatusReachableViaWiFi:
[TSMessageshowNotificationWithTitle:@"WiFi连接."type:TSMessageNotificationTypeSuccess];
break;
caseAFNetworkReachabilityStatusNotReachable:
[TSMessageshowNotificationWithTitle:@"断网了...,请检查你的网络是否连接!"type:TSMessageNotificationTypeError];
break;
}
}];
//开始监控
[operationManager.reachabilityManagerstartMonitoring];
}
效果图如下: