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

完结!

相关推荐
Cacciatore->1 分钟前
React 基本介绍与项目创建
前端·react.js·arcgis
摸鱼仙人~2 分钟前
React Ref 指南:原理、实现与实践
前端·javascript·react.js
teeeeeeemo4 分钟前
回调函数 vs Promise vs async/await区别
开发语言·前端·javascript·笔记
贵沫末22 分钟前
React——基础
前端·react.js·前端框架
aklry34 分钟前
uniapp三步完成一维码的生成
前端·vue.js
说私域38 分钟前
基于开源AI智能名片链动2+1模式的S2B2C商城小程序:门店私域流量与视频号直播融合的生态创新研究
人工智能·小程序·开源
Rubin9341 分钟前
判断元素在可视区域?用于滚动加载,数据埋点等
前端
爱学习的茄子42 分钟前
AI驱动的单词学习应用:从图片识别到语音合成的完整实现
前端·深度学习·react.js
用户38022585982442 分钟前
使用three.js实现3D地球
前端·three.js
程序无bug44 分钟前
Spring 面向切面编程AOP 详细讲解
java·前端