当使用Uniapp开发移动应用时,我们经常需要获取设备的连接状态,特别是WiFi连接状态。下面是一个简短的关于在Uniapp中获取WiFi连接状态的博客:
在Uniapp中,要获取设备的WiFi连接状态,我们可以利用uni.getNetworkType接口来实现。uni.getNetworkType接口可以获取当前网络状态,包括WiFi、3G、4G等类型,从而帮助我们判断设备是否连接了WiFi。
下面是一个简单的示例代码:
首先我们需要先获取以下地理位置:
//获取位置 uni.getSetting({ success(res) { // 请求地理定位权限 uni.authorize({ scope: 'scope.userLocation', success() { // 用户已经同意地理定位权限 // 3. 获取地理定位信息 uni.getLocation({ type: 'gcj02', // 获取的坐标类型 success: function(res) { }, fail: function(err) { uni.showToast({ title: '请打开位置信息并下拉刷新,否则会影响用户体验', icon: 'none' }) } }); }, fail() { uni.showToast({ title: '用户拒绝授权地理定位权限', icon: 'none' }) uni.showModal({ title: '提示', content: '请开启定位权限', success: function(res) { if (res.confirm) { uni.openSetting({ success: ( authRes ) => { console .log( authRes .authSetting ); } }); } else { uni.navigateBack({ delta: 1 }) } } }); } }) } })
获取成功之后,再开始检测wifi状态
// 初始化 uni.startWifi({ success() { console.log(111); if (that.platform == 'android') { console.log(222); // 获取wifi列表 uni.getWifiList({ success() { console.log(333); // 获取连接wifi的信息 uni.getConnectedWifi({ success(res) { console.log(res, 999); that.SSID = res.wifi.SSID console.log(that.wifis, 444); if (that.wifis != res.wifi.SSID && res.wifi .SSID != '') { that.set_status = false } if (that.wifis == res.wifi.SSID) { that.set_status = true } uni.hideLoading(); that.SSID = '' that.mess() }, fail() { that.set_status = false that.SSID = '' uni.showToast({ title: '获取失败', icon: 'none' }) that.mess() } }) }, fail() { uni.hideLoading(); that.message = '不在打卡范围' } }) } else if (that.platform == 'ios') { // 获取连接wifi的信息 uni.getConnectedWifi({ success(res) { console.log(res, 999); that.SSID = res.wifi.SSID console.log(that.wifis, 444); if (that.wifis != res.wifi.SSID) { that.set_status = false } if (that.wifis == res.wifi.SSID) { that.set_status = true } uni.hideLoading(); that.SSID = '' that.mess() }, fail() { that.SSID = '' that.set_status = false that.SSID = '' uni.showToast({ title: '获取失败', icon: 'none' }) that.mess() uni.hideLoading(); } }) } }, fail() { uni.showToast({ title: '初始化失败', icon: 'none' }) } })
这里需要注意的是由于安卓和苹果有些异同,所以要针对于不同手机型号做适配
下一篇文章我会讲出如何实时监测wifi连接状态,也就是说,如果切换wifi了或者关闭/打开了都会执行