在请求网络之前需要检查网络状态,如果没有网就可以走缓存
方法1
uni.getNetworkType({
success: function (res) {
console.log(res.networkType);//网络类型 wifi、2g、3g、4g、ethernet、unknown、none
if(res.networkType === "none"){
console.log("当前无网络");
}else{
console.log("有网络");
}
}
});
方法二
getNetworkType() {
var 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(function (res) {
console.log(res.isConnected);//当前是否有网络连接
console.log(res.networkType);//网络类型
if(res.isConnected === false){
console.log("当前无网络");
}else{
console.log("有网络");
}
});