0

uniapp监听网络状态 - 判断是否有网络

 1 year ago
source link: https://www.fly63.com/article/detial/12198
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

由于新机首次安装app的时候会出现:请求网络权限“是否允许使用数据”,如果用户很长时间没点击允许,就会出现app内接口请求永远返回失败的情况,需要用户清掉APP重新打开才能正常请求使用。

为解决这类问题,我们就需要监听网络状态,这边文章主要介绍uniapp判断是否有网,监听网络状态的问题,fly63前端网为大家介绍3种实现方案。

方法一:uni.getNetworkType

该方法用于获取网络类型。

uni.getNetworkType({
success: res=> {
if(res.networkType === "none"){//网络类型 wifi、2g、3g、4g、ethernet、unknown、none
console.log("当前无网络"); return;
}
console.log("有网络");
}
});

在实际使用时候,我们就需要用到定时器或者递归的方式来判断是否有网,等有网就进行相应请求操作,比如:

getNetwork(cb,time=300){
uni.getNetworkType({
success: function (res) {
if(res.networkType === "none"){//当前无网络
setTimeout(()=>{
this.getNetwork(cb);
},time);
return;
}
typeof cb=="function" && cb()
}
});
}

方法二:plus.networkinfo

使用html5+的plus下networkinfo模块用于获取网络信息。其中getCurrentType用于获取设备当前连接的网络类型:

getNetworkType() {
let types = {};
types[plus.networkinfo.CONNECTION_UNKNOW] = "Unknown";
types[plus.networkinfo.CONNECTION_NONE] = "None";
types[plus.networkinfo.CONNECTION_ETHERNET] = "Ethernet";
types[plus.networkinfo.CONNECTION_WIFI] = "WiFi";
types[plus.networkinfo.CONNECTION_CELL2G] = "2G";
types[plus.networkinfo.CONNECTION_CELL3G] = "3G";
types[plus.networkinfo.CONNECTION_CELL4G] = "4G";
console.log("Network: " + types[plus.networkinfo.getCurrentType()]);
}

方法三:uni.onNetworkStatusChange

经测试发现:该方法是无法实现监听的,官网所说的监听是指网络变化的时候被调用,实现监听要配合两个api使用:

uni.onNetworkStatusChange(res=>{
if(res.networkType=='none'){//res.networkType网络类型 wifi、2g、3g、4g、ethernet、unknown、none
console.log("当前无网络")
return;
}
console.log("有网络")
});

链接: https://www.fly63.com/article/detial/12198


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK