You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-native-NFC-Manager首次读写NFC新卡失败问题求解

解决方案

根因说明

当前代码仅申请了NfcTech.Ndef技术权限,未经过格式化的全新NFC卡仅支持NfcTech.NdefFormatable技术类型,因此首次扫描时技术匹配直接失败,无法执行后续写入操作。

具体修复方案

  • 扫描时同时注册Ndef和NdefFormatable两种技术类型,匹配成功后先判断卡的状态再执行对应操作
  • 针对未格式化的NdefFormatable卡,调用格式化方法直接写入NDEF数据,无需额外预处理步骤
  • 增加平台兼容性判断和错误兜底逻辑,避免异常无响应

修改后可直接使用的代码

import { Platform } from 'react-native';
import NfcManager, { NfcTech, Ndef } from 'react-native-nfc-manager';

const writeNfcCard = async () => {
  try {
    // 同时请求两种技术类型,兼容已格式化和未格式化的卡
    await NfcManager.requestTechnology([NfcTech.Ndef, NfcTech.NdefFormatable], {
      alertMessage: '准备写入NFC数据',
    });

    const bytes = Ndef.encodeMessage([Ndef.textRecord('Hello NFC')]);
    if (!bytes) return;

    // 读取卡支持的技术类型,选择对应写入逻辑
    const supportedTechs = await NfcManager.getTagTech();
    if (supportedTechs.includes(NfcTech.Ndef)) {
      // 已格式化的卡直接走原有写入逻辑
      await NfcManager.ndefHandler.writeNdefMessage(bytes);
    } else if (supportedTechs.includes(NfcTech.NdefFormatable)) {
      // 未格式化的卡先格式化再写入
      if (Platform.OS === 'ios' && parseInt(Platform.Version, 10) < 13) {
        throw new Error('当前系统版本不支持格式化全新NFC卡,请升级系统或先使用第三方工具格式化卡片');
      }
      await NfcManager.ndefFormatableHandler.formatNdef(bytes);
    }

    if (Platform.OS === 'ios') {
      await NfcManager.setAlertMessageIOS('NFC数据写入成功');
    }
  } catch (err) {
    console.warn('NFC写入失败:', err);
    if (Platform.OS === 'ios') {
      await NfcManager.setAlertMessageIOS(`写入失败: ${err.message || '未知错误'}`);
    }
  } finally {
    // 必须调用该方法释放NFC资源
    await NfcManager.closeTechnology();
  }
};

额外注意事项

  • 部分加密NFC卡、非标准厂商的特殊NFC卡本身不支持Ndef格式,即使执行格式化也会失败,这类情况需要给用户明确的操作提示
  • iOS端需要提前在Info.plist中配置NFCReaderUsageDescription权限,同时在项目能力中开启NDEF读写权限
  • 安卓端需要在AndroidManifest.xml中配置NFC相关权限,以及对应的NFC intent过滤器

内容的提问来源于stack exchange,提问作者krishna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:36:01