NFCAdapter.offDiscovered() 调用无效?(提供暂时方案
这个方法我发现不止我一个人调用没生效- -
这里提供个暂时方案
因为注销不掉nfc监听事件,只好确保整个生命周期内仅有一个nfc监听事件,所以全局定义:
1.一个变量nfcState(用于判断监听事件是否开启
2.一个方法(通过route事件去调用页面的scanNfc(),具体逻辑写在scanNfc内
nfcInit() {
if (!this.state.nfc) {
this.state.nfc = wx.getNFCAdapter();
}
let ab2str = (buffer) => {//转码
let dataView = new DataView(buffer);
let str = '';
for (let i = 0; i < dataView.byteLength; i++) {
let num16 = dataView.getUint8(i);
if (num16 / 16 >= 10) {
str += String.fromCharCode(65 + parseInt(num16 / 16) - 10);
} else {
str += String.fromCharCode(48 + parseInt(num16 / 16));
}
if (num16 % 16 >= 10) {
str += String.fromCharCode(65 + parseInt(num16 % 16) - 10);
} else {
str += String.fromCharCode(48 + parseInt(num16 % 16));
}
}
return str;
};
let errCode = {
13000: '本设备不支持NFC',
13001: '系统NFC开关未打开',
13010: '未知错误',
13019: '用户未授权',
13021: '已经开始NFC扫描',
13018: '尝试在未开始NFC扫描时停止NFC扫描',
13022: '标签已经连接',
13023: '尝试在未连接标签时断开连接',
13013: '未扫描到NFC标签',
13014: '无效的标签技术',
13015: '从标签上获取对应技术失败',
13024: '当前标签技术不支持该功能',
13017: '相关读写操作失败',
13016: '连接失败',
}
if (!this.state.nfcState) {
this.state.nfc.startDiscovery({
success: res => {
this.state.nfcState = true;
this.state.nfc.onDiscovered(res => {
console.log('nfc回调', res);
let code = ab2str(res.id);
// this.$msg('扫描成功!');
let routes = getCurrentPages();
// console.log(routes[routes.length-1].$vm.testNfc)
if (routes[routes.length - 1].$vm.scanNfc) {
routes[routes.length - 1].$vm.scanNfc(code)
}
});
},
fail: err => {
console.log('failed to discover:', err);
let content = errCode[err.errCode];
wx.showModal({
title: '错误',
showCancel: false,
content,
success: function(res) {
if (res.confirm) {
console.log('用户点击确定');
let routes = getCurrentPages();
// console.log(routes[routes.length-1].$vm.testNfc)
if (routes[routes.length - 1].$vm.openNfcFail) {
routes[routes.length - 1].$vm.openNfcFail()
}
}
}
});
}
});
}
}