背景:

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)
},

完结!

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部