#import "AFNetworkReachabilityManager.h"
- (BOOL)isNetWorkReachable{
__block CGRect rect = _nonNetworkLabel.frame; //这里的声明前面加__block。作用是在块里能够改动rect的值;
AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
[afNetworkReachabilityManager startMonitoring]; //开启网络监视器;
[afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
switch (status) {
case AFNetworkReachabilityStatusNotReachable:{
NSLog(@"网络不通:%f",
rect.origin.y );
_nonNetworkLabel.hidden = NO;
_nonNetworkLabel.text = @"网络不通..";
[self performSelector:@selector(hidden) withObject:nil afterDelay:3];
break;
}
case AFNetworkReachabilityStatusReachableViaWiFi:{
NSLog(@"网络通过WIFI连接:%f",
rect.origin.y );
_nonNetworkLabel.hidden = NO;
_nonNetworkLabel.text = @"网络通过WIFI连接..";
[self performSelector:@selector(hidden) withObject:nil afterDelay:3];
break;
}
case AFNetworkReachabilityStatusReachableViaWWAN:{
NSLog(@"网络通过流量连接:%f",
rect.origin.y );
_nonNetworkLabel.hidden = NO;
_nonNetworkLabel.text = @"网络通过流量连接..";
[self performSelector:@selector(hidden) withObject:nil afterDelay:3];
break;
}
default:
break;
}
}];
return [AFNetworkReachabilityManager sharedManager].isReachable;
}
- (void)hidden
{
_nonNetworkLabel.hidden = YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
if ([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0)
{
self.tabBar.translucent = NO;
}
else if ([[[UIDevice currentDevice]systemVersion]floatValue]
< 7.0){
}
//self.view.backgroundColor = [UIColor redColor];
//默认选择第几个
self.selectedIndex = 0;
self.nonNetworkLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, self.view.frame.size.height - 70, 160, 20)];
_nonNetworkLabel.backgroundColor = [UIColor blackColor];
_nonNetworkLabel.alpha = 0.6;
_nonNetworkLabel.textColor = [UIColor whiteColor];
_nonNetworkLabel.textAlignment = NSTextAlignmentCenter;
_nonNetworkLabel.font = [UIFont systemFontOfSize:12];
_nonNetworkLabel.hidden = YES;
[self.view addSubview:_nonNetworkLabel];
[self isNetWorkReachable];
}
//// 以下说一下原生的,地址
https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2
非常久后:
- (NetworkStatus)statusForNet
{
Reachability *reachability = [Reachability
reachabilityWithHostName:@"www.apple.com"];
NetworkStatus netStatus = [reachability
currentReachabilityStatus];
return netStatus;
}
- (BOOL)isHaveNetWork
{
if([self
statusForNet] ==
ReachableViaWiFi || [self
statusForNet] ==
ReachableViaWWAN){
return
YES;
}else{
return
NO;
}
}
- (void)replyAction:(UIButton *)sender
{
if ([self
isHaveNetWork]){
//
}else{
[self
showTextPrompt:nil
prompt:@"当前没有网络"];
sender.userInteractionEnabled =
NO;
}
sender.userInteractionEnabled =
YES;
}
说说为什么这个时候贴出这些代码, 关于项目的严谨性,断网的时候须要做一些预判的,我们常规的返回结果都是请求后给的,达不到想要的效果,比方没网时关闭用户交互并提示