網(wǎng)絡(luò).jpg
網(wǎng)絡(luò)
不論是APP 還是PC 想上網(wǎng)沖浪都離不開網(wǎng)絡(luò)蚕键。但是如果沒有網(wǎng)絡(luò)的時(shí)候應(yīng)該如何做才能讓用戶有更好的體驗(yàn)?zāi)兀?br> 看下效果圖:
無網(wǎng)絡(luò).PNG
實(shí)現(xiàn)
- 寫個(gè)單例(因?yàn)槲覀兠總€(gè)頁面都要檢測一下)
這個(gè)單例就是我們顯示沒有網(wǎng)絡(luò)的界面毅舆。
比如里面有:無網(wǎng)絡(luò)的圖片 以及刷新的按鈕!
主要代碼如下:
創(chuàng)建單例
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:@"網(wǎng)絡(luò)狀態(tài)待提升议谷,點(diǎn)擊重試" 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;
}
網(wǎng)絡(luò)檢查
// 輸出對應(yīng)的網(wǎng)絡(luò)狀態(tài)
- (void)reachabilityStatus
{
NetworkStatus status = self.reachability.currentReachabilityStatus;
if (status == self.status) {
}
self.status = status;
switch (status) {
case NotReachable:
NSLog(@"沒有聯(lián)網(wǎng)");
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;
}
}
界面調(diào)用
ZSCDetectNetWork *network = [ZSCDetectNetWork sharedInstance];
[network startDetectNetwork:self.view];
原理
就是根據(jù)網(wǎng)絡(luò)的狀態(tài)來選擇在傳入單例的view上顯示什么炉爆!
- 有網(wǎng):顯示正常狀態(tài)
- 無網(wǎng):顯示無網(wǎng)絡(luò)狀態(tài)