微信小程序读写NFC标签(实现NFC标签快速拉起小程序)实战

背景:

1、通过NFC进行写入,读取(读写NFC微信小程序只支持Andriod,ios可通过第三方工具写入或读取)
2、通过NFC标签贴近手机,自动拉起小程序某个页面(只要NFC标签里有urlScheme了,ios和Andriod都可以拉起)

前提:

1、准备NFC标签,并且NFC标签支持读写操作
2、申请好NFC标签的能力,通过modelId从服务端获取urlScheme(申请NFC标签能力必须是企业的认证,申请比较麻烦,跟着官方提供的教程,一步一步来)
实例化NFC、开启读取NFC、监听NFC、写入内容到NFC
  initNFC () {
    const __NFCInstance = wx.getNFCAdapter()
    this.setData({ NFCInstance: __NFCInstance })
    __NFCInstance.startDiscovery({
      success: (res) => {
        __NFCInstance.onDiscovered(this.discoverHandlerNfc)
      },
      fail: (err) => {
       	console.log(error)
      }
    })
  },

async discoverHandlerNfc (res) {
	// res:此res就是当前NFC标签里的内容,可根据转换自行取出里面需要用到的值
	const str = this.NFCbuf2hex(res.id)
	if (str ) {
		// 获取Ndef实例,通过Ndef读写
		const NDEF = await adapter.getNdef()
		// 建立连接
		NDEF.connect({
        	success: async (res) => {
        		// 写入records 兼容处理, 第一条ios,第二条Andriod
        		// urlScheme, 是通过小程序后台申请的设备能力后获得modeId,再通过modeId从服务端接口获取
          		const records = [
		            {
		              id: this.NFCStr2ab('mini-ios'),
		              tnf: 1,
		              type: this.NFCStr2ab('U'),
		              payload: this.NFCStr2ab('weixin://dl/xxxxxx/?t=xxxxxxxx', [0])
		            },
		            {
		              id: this.NFCStr2ab('mini-android'),
		              tnf: 4,
		              type: this.NFCStr2ab('android.com:pkg'),
		              payload: this.NFCStr2ab('com.tencent.mm')
		            }
		         ]
	             NDEF.writeNdefMessage({
	            	records: records,
		            success: (_res) => {
		              console.log('NDEF writeNdefMessage success -> ', _res)
		              // 写入成功 
		              // doSomething
		            },
		            fail: (_error) => {
		              console.log('NDEF writeNdefMessage _error -> ', _error)
		            }
	          	 })

       		 },
	         fail: (error) => {
	           console.log('NDEF error -> ', error)
	         }
          })

	}
	
},

// 把buffer转换为16进制字符串
NFCbuf2hex (arrayBuffer) {
  return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2)).join('')
},

// 把要写入的内容转换为buffer格式
NFCStr2ab (text, extraBytes) {
  const uriStr = encodeURIComponent(text)
  const bytes = []
  for (let i = 0; i < uriStr.length; i++) {
    const code = uriStr.charAt(i)
    if (code === '%') {
      const hex = uriStr.slice(i + 1, i + 3)
      const hexVal = parseInt(hex, 16)
      bytes.push(hexVal)
      i += 2
    } else {
      bytes.push(code.charCodeAt(0))
    }
  }
  if (extraBytes) {
    bytes.unshift(...extraBytes)
  }
  return new Uint8Array(bytes).buffer
},

// 取消监听
handleCancelNFC () {
   this.data.NFCInstance.offDiscovered(this.discoverHandlerNfc)
},

完结!

相关推荐
Mingyueyixi2 分钟前
Flutter Spacer引发的The ParentDataWidget Expanded(flex: 1) 惨案
前端·flutter
Rverdoser1 小时前
unocss 一直热更新打印[vite] hot updated: /__uno.css
前端·css
Bang邦1 小时前
使用nvm管理Node.js多版本
前端·node.js·node多版本管理
podoor1 小时前
wordpress不同网站 调用同一数据表
前端·wordpress
LJ小番茄2 小时前
Vue 常见的几种通信方式(总结)
前端·javascript·vue.js·html
黑狼传说2 小时前
前端项目优化:极致最优 vs 相对最优 —— 深入探索与实践
前端·性能优化
장숙혜2 小时前
前端-CDN的理解及CDN一些使用平台
前端
FakeOccupational3 小时前
nodejs 007:错误npm error Error: EPERM: operation not permitted, symlink
前端·npm·node.js
奶糖 肥晨3 小时前
react是什么?
前端·react.js·前端框架
亦舒.3 小时前
JSDelivr & NPM CDN 国内加速节点
前端·npm·node.js