网络
不论是APP 还是PC 想上网冲浪都离不开网络。但是如果没有网络的时候应该如何做才能让用户有更好的体验呢?
看下效果图:
实现
- 写个单例(因为我们每个页面都要检测一下)
这个单例就是我们显示没有网络的界面。
比如里面有:无网络的图片 以及刷新的按钮!
主要代码如下:
创建单例
static ZSCDetectNetWork *instance = nil;
+ (instancetype)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance.addView = nil;
instance.status = 10;
instance = [[[self class] alloc] init];
instance.photoImageView = [[UIImageView alloc] init];
instance.photoImageView.image = [UIImage imageNamed:@"noNetwork"];
[instance addSubview:instance.photoImageView];
instance.detectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
instance.detectBtn.titleLabel.font = [UIFont systemFontOfSize:14];
[instance.detectBtn setTitle:@"网络状态待提升,点击重试" forState:UIControlStateNormal];
[instance.detectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[instance.detectBtn addTarget:instance action:@selector(refreshNetwork) forControlEvents:UIControlEventTouchUpInside];
[instance addSubview:instance.detectBtn];
});
return instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}
网络检查
// 输出对应的网络状态
- (void)reachabilityStatus
{
NetworkStatus status = self.reachability.currentReachabilityStatus;
if (status == self.status) {
}
self.status = status;
switch (status) {
case NotReachable:
NSLog(@"没有联网");
instance.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1];
instance.frame = instance.addView.frame;
[instance.addView addSubview:instance];
[instance.photoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(instance).offset(170);
make.left.equalTo(instance).offset(instance.frame.size.width/2 - (198/2));
make.width.mas_equalTo(198);
make.height.mas_equalTo(151.5);
}];
[instance.detectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(instance.photoImageView.mas_bottom).offset(7);
make.left.equalTo(instance);
make.width.mas_equalTo(instance.frame.size.width);
make.height.mas_equalTo(40);
}];
break;
case ReachableViaWiFi:
NSLog(@"连接的是WIFI");
[instance removeFromSuperview];
break;
case ReachableVia4G:
NSLog(@"连接的是4G");
[instance removeFromSuperview];
break;
case ReachableVia3G:
NSLog(@"连接的是3G");
[instance removeFromSuperview];
break;
case ReachableVia2G:
NSLog(@"连接的是2G");
[instance removeFromSuperview];
break;
default:
break;
}
}
界面调用
ZSCDetectNetWork *network = [ZSCDetectNetWork sharedInstance];
[network startDetectNetwork:self.view];
原理
就是根据网络的状态来选择在传入单例的view上显示什么!
- 有网:显示正常状态
- 无网:显示无网络状态