使用uniapp实现小程序获取wifi并连接

一、背景

因业务需求,需要在小程序实现发现wifi和连接wifi。但由于Andriod和IOS有差异,所以实现起来有所区别。

先看官方文档 https://developers.weixin.qq.com/miniprogram/dev/framework/device/wifi.html

把连接基础流程了解后,发现二者流程和总结为:

二、流程

  1. startWifi: 初始化 Wi-Fi 模块
  2. getWifiList: 请求获取周边 Wi-Fi 列表。
  3. onGetWifiList: 获取到 Wi-Fi 列表数据事件
  4. setWifiList: (ios特有)设置 Wi-Fi 列表 中 AP 的相关信息,辅助用户进行连接
  5. onWifiConnected: 连接上 Wi-Fi 的事件回调

三、区别

个人实测后区别点在于:

  1. uni.startWifi 触发时:

    安卓:会调起"获取当前位置"权限的申请,用户通过后才能启动

    ios:直接通过

  2. uni.getWifiList 触发时:

    安卓:直接通过

    ios:会自动跳转到系统默认的app的设置页面,需用户手动切换到 系统设置-无线局域网,然后等wifi列表更新完成(菊花转完),再返回小程序后才能获取到

  3. setWifiList:

    安卓:无

    ios:特有

代码:

javascript 复制代码
<template>
  <view class="page">
    <view class="gc-box">
      <button @click="getConnectedWifi">获取当前连接wifi</button>
    </view>
    <view class="gc-box">
      <button @click="getWifiList">获取周围 WiFi</button>
    </view>

    <view class="gc-box">已连接:{{ connectedWifi.SSID }} </view>

    <view class="gc-box">默认连接密码:<input v-model="password" /> </view>

    <view class="gc-box">
      <view v-for="item in wifiList" :key="item.BSSID" class="item">
        <text class="title">{{ item.SSID }}</text>
        <button class="btn" @click="connectWifi(item)">连接</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      wifiList: [], // 存储WiFi列表
      connectedWifi: { SSID: '' }, // 存储当前已连接wifi
      password: '', // 密码
    }
  },

  onLoad() {
    this.onWifiConnected()
    this.onGetWifiList()
  },

  methods: {
    /** 启动wifi */
    startWifi() {
      return new Promise((resolve, reject) => {
        uni.startWifi({
          success: (res) => {
            console.log('启动wifi 成功', res)
            resolve(true)
          },
          fail: (err) => {
            console.error('启动wifi 失败', err)
            uni.showModal({ content: err.errMsg, showCancel: false })
            reject(new Error(err))
          },
        })
      })
    },

    /** 获取wifi列表, ios和android 各不相同,具体看顶部资料 */
    async getWifiList() {
      const hasStart = await this.startWifi()
      if (hasStart !== true) return
      uni.getWifiList({
        success: (res1) => {
          console.log('获取wifi列表命令发送 成功', res1)
        },
        fail: (err) => {
          console.error('获取wifi列表 失败', err)
          uni.showModal({ content: err.errMsg, showCancel: false })
        },
      })
    },

    /** 监听获取wifi列表 */
    onGetWifiList() {
      uni.onGetWifiList((res) => {
        console.log('监听获取wifi列表', res)
        const { wifiList } = res
        // 过滤同名WiFi信号
        const filterList = wifiList.reduce((result, item) => {
          const index = result.findIndex((v) => {
            return v.SSID === item.SSID
          })
          if (index < 0) {
            result.push(item)
          } else if (item.signalStrength > result[index].signalStrength) {
            result[index] = item
          }
          return result
        }, [])
        console.log('过滤同名后', filterList)
        this.wifiList = filterList
      })
    },

    /** 连接某个 Wi-Fi */
    connectWifi(wifi) {
      console.log('选中的wifi:', wifi)
      this.connectedWifi = { SSID: '' }
      uni.connectWifi({
        SSID: wifi.SSID,
        password: this.password,
        success: (res) => {
          console.log('wifi连接命令发送 成功:', res)
        },
        fail: (err) => {
          console.error('wifi连接 失败:', err)
          uni.showModal({ content: err.errMsg, showCancel: false })
        },
      })
    },

    /**  监听wifi连接状态 */
    onWifiConnected() {
      uni.onWifiConnected((res) => {
        console.log('监听wifi连接状态', res)
        this.connectedWifi = res.wifi
      })
    },

    /** 获取当前连接的wifi */
    async getConnectedWifi() {
      this.connectedWifi = { SSID: '' }
      const hasStart = await this.startWifi()
      if (hasStart !== true) return
      uni.getConnectedWifi({
        success: (res) => {
          console.log('获取当前连接的wifi 成功', res)
          this.connectedWifi = res.wifi // 当前连接的wifi的信息
          // this.connectedWifiSSID = res.wifi.SSID
        },
        fail: (err) => {
          console.error('获取当前连接的wifi 失败:', err)
          uni.showModal({ content: err.errMsg, showCancel: false })
        },
      })
    },
  },
}
</script>

<style>
.item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  border-bottom: 2rpx solid #ddd;
  padding: 16rpx 0;
}
.item .title {
  flex: 1;
}
input {
  border-bottom: 2rpx solid #ddd;
}
</style>
相关推荐
weixin_lynhgworld2 小时前
淘宝扭蛋机小程序系统开发:重塑电商互动模式
大数据·小程序
996幸存者4 小时前
uni-app区域选择、支持静态、动态数据
微信小程序·uni-app
ᥬ 小月亮5 小时前
Uniapp编写微信小程序,绘制动态圆环进度条
微信小程序·小程序·uni-app
耶啵奶膘9 小时前
uniapp+vue3——通知栏标题纵向滚动切换
uni-app
The_era_achievs_hero12 小时前
UniappDay03
vue.js·微信小程序·uni-app
说私域15 小时前
技术赋能与营销创新:开源链动2+1模式AI智能名片S2B2C商城小程序的流量转化路径研究
人工智能·小程序·开源
游戏开发爱好者81 天前
没有 Mac,如何上架 iOS App?多项目复用与流程标准化实战分享
android·ios·小程序·https·uni-app·iphone·webview
weixin_lynhgworld1 天前
代驾小程序系统开发:引领出行行业数字化转型
小程序
Python大数据分析1 天前
uniapp之微信小程序标题对其右上角按钮胶囊
微信小程序·小程序·uni-app
yzx9910131 天前
JS与Go:编程语言双星的碰撞与共生
java·数据结构·游戏·小程序·ffmpeg