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

.NET Maui中Plugin.NFC报‘Tag is not NDEF-compliant’错误的解决方法

解决Plugin.NFC写入新NFC卡时“Tag is not NDEF-compliant”的问题

新的空白NFC卡默认未被格式化为NDEF兼容格式,直接写入会触发该错误。NFC Tools等工具的“初始化”操作本质是完成了NDEF格式化,因此能正常写入。你需要在代码中加入NDEF格式化逻辑,对新卡片先初始化再执行写入。

修正后的代码

async Task Publish()
{               
    try
    {     
        // 传入true开启自动格式化支持
        CrossNFC.Current.StartPublishing(true);
    }
    catch (Exception ex)
    {
        await RaiseError(ex.Message);
    }
}

async void Current_OnTagDiscovered(ITagInfo tagInfo, bool format)
{
    if (!CrossNFC.Current.IsWritingTagSupported)
    {
        await RaiseMessage_("设备不支持NFC卡片写入");
        return;
    }
    
    try
    {
        // 核心:对非NDEF兼容的卡片执行格式化初始化
        if (!tagInfo.IsNdefCompliant && format)
        {
            bool isFormatted = await CrossNFC.Current.FormatTagAsync(tagInfo);
            if (!isFormatted)
            {
                await RaiseError("卡片初始化失败,无法转换为NDEF兼容格式");
                return;
            }
        }

        // 二次确认卡片状态
        if (!tagInfo.IsNdefCompliant)
        {
            await RaiseError("该卡片不支持NDEF格式,且无法初始化");
            return;
        }

        NFCNdefRecord record = new NFCNdefRecord
        {
            TypeFormat = NFCNdefTypeFormat.Mime,
            MimeType = "application/com.companyname.nfcsample",
            Payload = NFCUtils.EncodeToByteArray("Hithere") // 修正原代码多余的分号语法错误
        };

        tagInfo.Records = new[] { record };
        // 使用异步方法避免线程阻塞
        await CrossNFC.Current.PublishMessageAsync(tagInfo, false);
        
    }
    catch (Exception Ex)
    {
        await RaiseError("写入失败\n" + Ex.Message);            
    }
}

关键说明

  • 格式化逻辑:通过FormatTagAsync方法完成新卡片的NDEF初始化,这是解决报错的核心步骤
  • 参数利用:StartPublishing(true)中的true表示允许自动格式化,事件参数format同步该状态,用于判断是否执行格式化操作
  • 语法修正:原代码中Payload行末尾的分号是语法错误,需移除
  • 异步优化:改用PublishMessageAsync异步方法,避免UI线程阻塞

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:10:36