欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

微信小程序如何检测接收iBeacon信号

前话

微信小程序开发带着许多坑,最近就遇到了个需求,检测iBeacon来进行地点签到。

(╯▔皿▔)╯

微信小程序对于iBeacon的文档也写的十分精简,只简单介绍了每个接口的作用,这就导致我以为简单调用单个接口即可实现功能,因此我就写出了这样的错误代码逻辑 :

(╯‵□′)╯︵┻━┻

wx.startBeaconDiscovery({
    uuids: ['xxxxx'],
    success(res){
        console.log('签到成功')
    },
    fail(err){
        console.log('签到失败')
    }
})
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

结果是,点击签到按钮调用该接口的时候,几乎都是签到失败

(╯‵□′)╯炸弹!•••*~●。

当然,最后还是谷歌解决了,因为前人也踩了这个坑,因此我还是搬运过来,让后人少受熬夜之苦 (;´༎ຶД༎ຶ`)

正题

废话不多说,如果你要检测接收iBeacon信号,建议按照这样的接口调用步骤:

       wx.stopBeaconDiscovery # 停止扫描
        ↑
       setTimeout # 超时设置
        ↑
开始 → wx.startBeaconDiscovery # 开始扫描
        ︱
        ︱―fail(err)→结束
        ︱
       success(res)
        ↓
       wx.onBeaconUpdate # 监听iBeacon信号
        ︱  
        ︱―fail(err)→结束
        ︱
       success(res)
        ↓
       TODO
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

最后,我的代码如下:

var devices = [];

// 开始扫描
wx.startBeaconDiscovery({
    uuids: uuidArray,
    success: function () {
        console.log("开始扫描设备...");
        // 监听iBeacon信号
        wx.onBeaconUpdate(function (res) {
            // 请注意,官方文档此处又有BUG,是res.beacons,不是beacons。
            if (res && res.beacons && res.beacons.length > 0) {
                devices = res.beacons;
                // 此处最好检测rssi是否等于0,等于0的话信号强度等信息不准确。我是5秒内重复扫描排重。
            }
        });
    }
});

// 超时停止扫描
setTimeout(function () {
    wx.stopBeaconDiscovery({
        success: function () {
            console.log("停止设备扫描!");
            console.log(devices);
        }
    });
}, 5 * 1000);
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

  • 19

  • 20

  • 21

  • 22

  • 23

  • 24

  • 25

  • 26

  • 27

OK,问题似乎不经意间被完美解决了( •̀ ω •́ )y

来自 https://blog.csdn.net/pwc1996/article/details/78083268

普通分类: