,小程序使用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',
});
},
});
};
