先上代码:
<template>
<view class="home">
<button class="home-but" @click="authorizeLocation">扫码连WIFI</button>
</view>
</template>
<script>
export default {
data() {
return {}
},
onLoad() {
},
methods: {
authorizeLocation() {
uni.authorize({
scope: 'scope.userLocation',
success: () => {
// 用户授权成功后,开始连接WiFi
this.startWifi();
},
fail: () => {
uni.showToast({
title: '位置信息授权失败',
icon: 'none'
});
}
});
},
// 开启WiFi模块
startWifi() {
uni.startWifi({
success: (success) => {
console.log("success", success)
this.detectionWifi();
},
fail: (err) => {
console.log("开启WiFi模块失败", err);
// 开启WiFi模块失败后的处理逻辑
}
});
},
// 检测当前是否链接该网络
detectionWifi() {
wx.getConnectedWifi({
success: (res) => {
console.log(res);
if(res.wifi.SSID === 'dlbsx_3'){
uni.showToast({
title: '请勿重复连接'
})
return;
}else{
this.linkWifi();
}
},
fail: (err) => {
console.log(err);
this.linkWifi();
}
})
},
// 连接wifi
linkWifi(){
uni.showLoading({
title: '连接中...'
})
uni.connectWifi({
SSID: '', //wifi名称
//BSSID:'你的设备唯一值',//Wi-Fi 设备 BSSID
password: '', // 这里需要用户输入真实的WiFi密码
success: () => {
// console.log("WiFi连接成功");
// 连接成功后的处理逻辑
uni.showToast({
title: 'WiFi连接成功'
})
},
fail: (err) => {
// console.log("WiFi连接失败", err);
// 连接失败后的处理逻辑
uni.showToast({
title: 'WiFi连接失败'
})
}
});
}
}
}
</script>
<style>
.home {
width: 100%;
}
.home-but {
width: 50%;
height: 80rpx;
margin-top: 100rpx;
background-color: #1989FA;
color: #FFFFFF;
letter-spacing: 5rpx;
line-height: 80rpx;
outline: none;
box-shadow: 2px 2px 5px #eeeeee;
}
</style>
原创作者:吴小糖
创作时间:2024.3.25