首先通過wx.getNFCAdapter()來獲取nfc實例
然后調(diào)用startDiscovery獲取當前手機nfc狀態(tài)
已經(jīng)打開了nfc的就可以調(diào)用監(jiān)聽方法onDiscovered
監(jiān)聽到數(shù)據(jù)后setData把數(shù)據(jù)展示出來就ok了寞焙,方法如下
nfcRead() {
console.log('nfc')
const nfc = wx.getNFCAdapter()
this.nfc = nfc
let _this = this
function discoverHandler(res) {
console.log('discoverHandler', res)
const data = new Uint8Array(res.id)
let str = ""
data.forEach(e => {
let item = e.toString(16)
if (item.length == 1) {
item = '0' + item
}
item = item.toUpperCase()
console.log(item)
str += item
})
_this.setData({
newCardCode: str
})
console.log(str)
wx.showToast({
title: '讀取成功依溯!',
icon: 'none'
})
}
nfc.startDiscovery({
success(res) {
console.log(res)
wx.showToast({
title: 'NFC讀取功能已開啟誉己!',
icon: 'none'
})
nfc.onDiscovered(discoverHandler)
},
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: '系統(tǒng)NFC開關(guān)未打開!',
icon: 'none'
})
break;
case 13019:
wx.showToast({
title: '用戶未授權(quán)!',
icon: 'none'
})
break;
case 13010:
wx.showToast({
title: '未知錯誤!',
icon: 'none'
})
break;
}
}
})
},