微信小程序读写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)
},

完结!

相关推荐
csj504 分钟前
前端基础之《React(7)—webpack简介-ESLint集成》
前端·react
Jonathan Star4 分钟前
CSS margin 折叠现象的实际代码示例
javascript·css·css3
咚咚咚小柒9 分钟前
【前端】Webpack相关(长期更新)
前端·javascript·webpack·前端框架·node.js·vue·scss
2501_916008899 分钟前
前端工具全景实战指南,从开发到调试的效率闭环
android·前端·小程序·https·uni-app·iphone·webview
诸葛韩信11 分钟前
Webpack与Vite的常用配置及主要差异分析
前端·webpack·node.js
IT_陈寒15 分钟前
Vite 5震撼发布!10个新特性让你的开发效率飙升200% 🚀
前端·人工智能·后端
一路向前的月光20 分钟前
uniapp(5)滚动列表scroll-view
前端·javascript·uni-app
Hilaku44 分钟前
就因为package.json里少了个^号,我们公司赔了客户十万块
前端·javascript·npm
晴殇i1 小时前
尤雨溪创立的 VoidZero 完成 1250 万美元 A 轮融资,加速整合前端工具链生态
前端·vue.js
一大树1 小时前
MutationObserver 完整用法指南
前端