uniapp点击按钮连接wifi?

时间:2024-03-31 21:53:55
<view>
  <button class="but" bindtap="connectToWifi">点击连接WiFi</button>
</view>       

js:

Page({
  // 页面数据
  data: {
    wifiConnected: false
  },

  onLoad: function () {
    this.checkWifiPermission();
  },

  // 检查 WiFi 权限
  checkWifiPermission: function () {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.wifi']) {
          wx.authorize({
            scope: 'scope.wifi',
            success: () => {
              console.log('用户已同意连接 WiFi 的权限');
            },
            fail: () => {
              console.log('用户拒绝了连接 WiFi 的权限');
            }
          });
        }
      }
    });
  },

  // 处理连接 WiFi 操作
  connectToWifi: function () {
    wx.startWifi({
      success: (res) => {
        console.log('Wi-Fi 模块已开启');
        wx.connectWifi({
          SSID: 'xiaozhao',
          password: '11111111',
          success: (res) => {
            console.log('Wi-Fi 连接成功', res);
            this.setData({ wifiConnected: true });
            wx.showToast({
              title: 'Wi-Fi 连接成功',
              icon: 'success',
              duration: 2000
            });
          },
          fail: (err) => {
            console.error('Wi-Fi 连接失败', err);
            wx.showToast({
              title: 'Wi-Fi 连接失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
      },
      fail: (err) => {
        console.error('Wi-Fi 模块开启失败', err);
      }
    });
  }
});

app.json:

 "permission": {
    "scope.userLocation": {
      "desc": "用于连接 Wi-Fi"
    }
  },

css:

page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.but {
  margin-top: 50%;
}

效果: