一:无网络页面的创建
①创建继承自UIView的NoWebView文件并绘制相应的无网络界面
这里我是用XIB文件绘制的,要留出一个Button,用来重新加载,将其响应事件添加到对应的.m文件中。
②上传点击事件(我用的是block语法)
(.h文件)
//定义一个blocktypedef void(^ClickBlock)();@interface NoNewView : UIView//防止block暴露在外-(void)setupWithClickBlock:(ClickBlock)block;
(.m文件)
//将block当做属性@property (nonatomic,strong) ClickBlock myBlock;-(void)setupWithClickBlock:(ClickBlock)block{ _myBlock = block; }//button点击事件- (IBAction)ClickButton:(id)sender { if (_myBlock != nil) { _myBlock(); } }
二:判断当前网络是否可用
首先引入两个第三方库Reachability和AFNetworkReachabilityManager
.h文件中对外声明一个方法,用来获取到当前网络状态。
-(BOOL)isNetWorking;
.m文件中
声明两个全局变量
@property(nonatomic,strong)AFNetworkReachabilityManager *reach;@property (nonatomic,assign) BOOL isNetGoing;
self.isNetGoing = NO; self.reach= [AFNetworkReachabilityManager sharedManager]; //这个是网络可用时的回调 __weak AppDelegate*weakSelf = self; [self.reach setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusUnknown: weakSelf.isNetGoing = NO; break; case AFNetworkReachabilityStatusNotReachable: weakSelf.isNetGoing = NO; break; case AFNetworkReachabilityStatusReachableViaWiFi: weakSelf.isNetGoing = YES; break; case AFNetworkReachabilityStatusReachableViaWWAN: weakSelf.isNetGoing = YES; break; default: weakSelf.isNetGoing = YES; break; } }]; [self.reach startMonitoring];
外界通过获取isNetWoriking的值,来判断当前网络是否可用
- (BOOL)isNetWorking{ return self.isNetGoing;}
三:根视图的创建
.h文件
@class NoNewView;typedef void(^ClickBlock)();@interface RootUIViewController : UIViewController@property(nonatomic,strong)NoNewView *View_noNet;//如果没有网络,执行某操作,并隐藏原视图显示无网络视图-(void)ifNoNetWork:(ClickBlock)action Hidden:(id)View;
.m文件
@property(nonatomic,strong)ClickBlock Action;@property(nonatomic,strong)UITableView *TV;@property(nonatomic,strong)UICollectionView *CL;
-(void)ifNoNetWork:(ClickBlock)action Hidden:(id)View{ //判断是否是某个类 if ([View isKindOfClass:[UITableView class]]) { self.TV=View; }else if ([View isKindOfClass:[UICollectionView class]]){ self.CL=View; } //用户点击了重新加载 _Action=action; [self.View_noNet setupWithClickBlock:_Action]; if (self.View_noNet!=nil) { [self.view addSubview:self.View_noNet]; }}
这样一来,在每个视图获取网络数据前,添加上
-(void)getNetWork{ [self ifNoNetWork:^{ [self getNetWork]; } Hidden:self.CL];/* 获取网络数据*/}
就可以到达响应的目的