export async function startNfcScan() { const nfcAdapter = wx.getNFCAdapter(); await nfcAdapter.startDiscovery(); return new Promise((resolve, reject) => { try { nfcAdapter.onDiscovered((res) => { console.log("onDiscovered", res); const arr = Array.from(new Int8Array(res.id)); resolve(arr); }); } catch (e) { reject(e); } }); } export class WeixinNfcUtil { nfcAdapter = null; discoveredListenerList = []; /** * @type {Function} */ _discoveredHandler = null; constructor() { this.nfcAdapter = wx.getNFCAdapter(); this._discoveredHandler = this.discoveredHandler.bind(this); this.nfcAdapter.onDiscovered(this._discoveredHandler); } /** * 是否开启NFC * NOTE 微信无法判断是否开启 * @returns {boolean} true 已开启 */ static async isNfcEnabled() { try { wx.getNFCAdapter(); return true; } catch (e) { console.error(e); return false; } } discoveredHandler(res) { console.log("onDiscovered", res); const arr = Array.from(new Int8Array(res.id)); this.discoveredListenerList.forEach((cb) => { cb(arr); }); } /** * * @param {Function} cb */ addDiscoveredListener(cb) { this.discoveredListenerList.push(cb); } async startNfcScan() { return await this.nfcAdapter.startDiscovery(); } async stopNfcScan() { this.nfcAdapter.offDiscovered(this._discoveredHandler); return await this.nfcAdapter.stopDiscovery(); } static async scan() { const weixinNfcUtil = new WeixinNfcUtil(); return await new Promise((resolve, reject) => { weixinNfcUtil .startNfcScan() .then(() => { weixinNfcUtil.addDiscoveredListener((res) => { weixinNfcUtil.stopNfcScan(); resolve(res); }); }) .catch(reject); }); } }