最近参加挑战杯在开发项目的时候遇到了一个小程序识别nfc的需求,经过翻阅官方文档。
最终实现了对nfc芯片的识别。
实现代码如下:
代码语言:javascript复制read() {
var that = this;
const adapter = wx.getNFCAdapter();
uni.showToast({
'icon': 'success',
'title': '监听成功'
})
adapter.onDiscovered(res => {
let tagId = res.id;
if (res.techs.includes(adapter.tech.nfcA)) {
const uid = that.get(res);
that.handle(uid);
} else {
wx.showToast({
title: '卡片类型有误!',
icon: 'error'
});
}
})
adapter.startDiscovery({
success: function(res) {
console.log('startDiscovery:', res);
},
fail(err) {
console.log('failed to discover:', err)
if (!err.errCode) {
wx.showToast({
title: '请检查NFC功能是否正常!',
icon: 'none'
})
return
}
switch (err.errCode) {
case 13000:
wx.showToast({
title: '设备不支持NFC!',
icon: 'none'
})
break;
case 13001:
wx.showToast({
title: '系统NFC开关未打开!',
icon: 'none'
})
break;
case 13019:
wx.showToast({
title: '用户未授权!',
icon: 'none'
})
break;
case 13010:
wx.showToast({
title: '未知错误!',
icon: 'none'
})
break;
}
}
})
},
get(res) {
const byteArray = new Uint8Array(res.id);
let uid = '';
for (let i = 0; i < byteArray.length; i ) {
let hex = byteArray[i].toString(16).toUpperCase();
if (hex.length === 1) {
hex = '0' hex;
}
uid = hex;
}
return uid;
},
handle(uid) {
uni.showModal({
title: '呼应上了',
content: '智囊编号:' uid,
confirmText: '打开',
cancelColor: '关闭',
success(res) {
if (res.confirm) {
uni.navigateTo({
url: '../image/image?uid=' uid // 跳转到目标页面,并携带 UID 参数
});
} else {
console.log('quxiao');
}
}
});
}
推荐一个项目
工学云打卡习讯云打卡自动化打卡体验地址:https://liangzhizhangyu.com