Cordova Ionic NFC标签写入失败:提示标签容量为0字节求助
Let's break down what's likely causing this issue and walk through actionable fixes:
Common Causes & Solutions
1. The erase() Method Isn't Compatible With Your Tag
Most NDEF-compliant tags (like your 8Kbit model) don't require explicit erasing—writing new content automatically overwrites existing data. The erase() call might be triggering an incorrect capacity check or failing to interact properly with your tag's chip.
Fix: Remove the erase() step entirely and try writing directly:
this.nfc.addNdefListener( () => { console.log("Successfully attached NDEF listener"); }, (err: any) => { console.log("error attaching ndef listener", err); } ).subscribe( (event) => { console.log("received NDEF message", event); // Log tag details to debug capacity detection console.log("Tag supported techs:", event.tag.techs); console.log("Reported tag max size:", event.tag.maxSize); if (this.isWriting) { // Simplify the text record (optional params can sometimes cause unexpected issues) const textRecord = this.ndef.textRecord("Hello world"); this.nfc.write([textRecord]) .then( () => { console.log("Successfully wrote to the tag!"); }) .catch( (err: any) => { console.log("Failed to write to tag:", err); }); } });
2. Your Tag Isn't Properly NDEF-Formatted
If the tag hasn't been initialized with an NDEF structure, the Cordova NFC plugin may fail to detect its actual capacity, reporting 0 bytes instead of the true 8Kbit (1KB) size.
Fix:
- Use a native NFC app (like Android's built-in NFC tools or a trusted third-party app) to format the tag as NDEF first.
- Retest your code after formatting is complete.
3. Outdated NFC Plugin Version
Older versions of cordova-plugin-nfc have known compatibility gaps with certain 13.56MHz tag models, including incorrect capacity detection.
Fix:
Update the plugin to the latest version via CLI:
cordova plugin rm cordova-plugin-nfc cordova plugin add cordova-plugin-nfc
4. Missing or Misconfigured Permissions
Double-check that your app has the required NFC permissions in AndroidManifest.xml:
<uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="true" />
Extra Debugging Tips
- Inspect tag tech details: The
event.tag.techsarray in your listener will list the NFC technologies the plugin recognizes. For your tag, you should see entries likeNdefand possiblyMifareUltralightorNtag21X. - Test with a known-compatible tag: If possible, try a well-documented NDEF tag (like NTAG215) to rule out hardware-specific compatibility issues.
内容的提问来源于stack exchange,提问作者Stacknerd

