收藏
回答

小程序靠近NFC获取ID为什么会唤起系统自带的弹框?

,小程序使用NFC靠近NFC设备获取id,重复扫描会出现系统弹框,并且也获取不到ID了,相关代码如下:

const initNFC = () => {

  if (!wx.getNFCAdapter) {

    uni.showToast({

      title: '当前设备不支持NFC功能',

      icon: 'none',

    });

    return;

  }

  const adapter = wx.getNFCAdapter();

  nfcAdapter.value = adapter;

  adapter.onDiscovered((res) => {

    const uid = res.id;

    const hexUid = arrayBufferToHex(uid);

    formData.rfidId = hexUid;

    stopNFCListening();

    nfcDialogVisible.value = false;

  });

};

function arrayBufferToHex(buffer) {

  const view = new Uint8Array(buffer);

  let hex = '';

  for (let i = 0; i < view.length; i++) {

    hex += view[i].toString(16).padStart(2, '0');

  }

  return hex;

}

const stopNFCListening = () => {

  if (nfcAdapter.value && isListening.value) {

    nfcAdapter.value.stopDiscovery({

      success: (res) => {

        isListening.value = false;

      },

      fail: (res) => {

        uni.showToast({

          title: '停止NFC监听失败',

          icon: 'none',

        });

      },

    });

  }

};

点击按钮获取的时候方法

const openNFCDialog = () => {

  console.log('打开NFC弹框', nfcAdapter.value);

  if (isListening.value) {

    stopNFCListening();

    return;

  }


  nfcAdapter.value.startDiscovery({

    success: () => {

      nfcDialogVisible.value = true;

      isListening.value = true;

    },

    fail: (err) => {

      uni.showToast({

        title: `启动NFC搜索失败:${JSON.stringify(err)}`,

        icon: 'none',

      });

    },

  });

};

回答关注问题邀请回答
收藏

1 个回答

  • 智能回答 智能回答 本次回答由AI生成
    2025-10-15
    有用
登录 后发表内容