**
微信小程序开发nfc读取
**
(注释微信官方api,仅支持安卓,不支持苹果ios)官方文档
上代demo
<template>
<div class="nfc">
<u-navbar leftIcon="arrow-leftward" bgColor="#ffffff" leftIconColor="#000000" title="nfc管理" :autoBack="true"
:safeAreaInsetTop="true" :placeholder="true" :fixed="true" titleStyle="font-size: 48rpx;color:#000000">
</u-navbar>
<button class="" @tap="read()">读取NFC</button>
<textarea class="txtarea" disabled :value="readData" placeholder="nfc卡数据" />
<textarea class="txtarea" style="margin-top: 26rpx;" v-model="writeTxt" maxlength="124"
placeholder="请输入需要写入nfc的数据" />
<button class="" @tap="write()">写入NFC</button>
<button class="btn" @click="cleardata()">重置页面</button>
</div>
</template>
<script>
export default {
data() {
return {
nfc: null,
readData: '',
writeTxt: '',
}
},
onLoad() {
this.nfc = wx.getNFCAdapter()
// 开始监听 不能缺少
this.nfc.startDiscovery({
success(res) {
console.log("建立连接", res)
},
fail(err) {
console.log('建立连接err:', err)
}
})
},
onShow() {
},
onReady() {},
methods: {
read() { //读取
// 绑定监听 NFC 标签
this.nfc.onDiscovered(res => {
console.log("监听的数据", res)
if (res.messages && res.messages[0].records && res.messages[0].records[0].payload) {
this.getData(res.messages[0].records[0].payload)
} else {
uni.showToast({
icon: 'none',
title: '卡片中无数据'
})
}
})
},
getData(buffer) { //解析nfc卡中的数据
const view = new Uint8Array(buffer);
const txt = decodeURIComponent(escape(String.fromCharCode(...view))) // 兼容性写法
this.readData = txt
uni.showToast({
icon: 'none',
title: '数据读取成功'
})
console.log(txt);
},
write() {
// 获取NFC实例
// 绑定监听 NFC 标签
this.nfc.onDiscovered(res => {
console.log("写入监听连接", res)
const NFC = this.nfc.getNdef()
//进行写入
NFC.connect({
success: () => {
NFC.writeNdefMessage({
uris: [this.writeTxt], //写入类型
success: (res1) => {
uni.showToast({
icon: 'none',
title: '数据写入成功'
})
console.log('数据写入成功', res1)
},
fail: () => {
uni.showToast({
icon: 'none',
title: '数据写入失败'
})
console.log('数据写入失败')
},
})
},
})
})
},
cleardata() {
this.readData = ''
this.writeTxt = ''
},
},
onHide() {
if (this.nfc) {
this.nfc.stopDiscovery()
}
}
}
</script>
<style lang="scss" scoped>
.nfc {
padding-bottom: 50rpx;
height: calc(100vh - 50rpx);
background: #FBFBFB;
overflow-x: hidden;
overflow-y: auto;
padding: 32rpx;
.btn {
margin-top: 26rpx;
}
.txtarea {
border: 2rpx solid #d5d5d5;
width: 100%;
}
}
</style>