Empezando
-
Instalar el paquete
Ventana de terminal npm i @capgo/capacitor-nfcVentana de terminal pnpm add @capgo/capacitor-nfcVentana de terminal yarn add @capgo/capacitor-nfcVentana de terminal bun add @capgo/capacitor-nfc -
Sincronización con proyectos nativos
Ventana de terminal npx cap syncVentana de terminal pnpm cap syncVentana de terminal yarn cap syncVentana de terminal bunx cap sync
Configuración
Section titled “Configuración”iOS Configuración
Section titled “iOS Configuración”Agregue la descripción de uso de NFC a su Info.plist:
<key>NFCReaderUsageDescription</key><string>This app needs NFC access to read and write tags</string>Habilite la capacidad de lectura de etiquetas de comunicación de campo cercano en su proyecto Xcode.
Android Configuración
Section titled “Android Configuración”Agregue el permiso NFC a su AndroidManifest.xml:
<manifest> <uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="false" /></manifest>Comience a escanear en busca de etiquetas NFC
Section titled “Comience a escanear en busca de etiquetas NFC”import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.startScanning({ invalidateAfterFirstRead: false, // Keep session open (iOS) alertMessage: 'Hold a tag near the top of your device.',});
const listener = await CapacitorNfc.addListener('nfcEvent', (event) => { console.log('Tag detected:', event.type); console.log('Tag ID:', event.tag?.id); console.log('NDEF message:', event.tag?.ndefMessage);});Leer etiqueta NFC
Section titled “Leer etiqueta NFC”await CapacitorNfc.addListener('nfcEvent', (event) => { if (event.tag?.ndefMessage) { event.tag.ndefMessage.forEach(record => { console.log('TNF:', record.tnf); console.log('Type:', record.type); console.log('Payload:', record.payload);
// Decode text record if (record.tnf === 1 && record.type[0] === 0x54) { // Text record const langLen = record.payload[0] & 0x3f; const text = new TextDecoder().decode( new Uint8Array(record.payload.slice(langLen + 1)) ); console.log('Text:', text); } }); }});Escribir en etiqueta NFC
Section titled “Escribir en etiqueta NFC”// Prepare a text recordconst encoder = new TextEncoder();const langBytes = Array.from(encoder.encode('en'));const textBytes = Array.from(encoder.encode('Hello NFC'));const payload = [langBytes.length & 0x3f, ...langBytes, ...textBytes];
await CapacitorNfc.write({ allowFormat: true, records: [ { tnf: 0x01, // TNF Well-known type: [0x54], // 'T' for Text id: [], payload, }, ],});
console.log('Tag written successfully');Escribir URL en etiqueta NFC
Section titled “Escribir URL en etiqueta NFC”const url = 'https://capgo.app';const urlBytes = Array.from(new TextEncoder().encode(url));
await CapacitorNfc.write({ allowFormat: true, records: [ { tnf: 0x01, // TNF Well-known type: [0x55], // 'U' for URI id: [], payload: [0x01, ...urlBytes], // 0x01 = https:// }, ],});Borrar etiqueta NFC
Section titled “Borrar etiqueta NFC”await CapacitorNfc.erase();console.log('Tag erased');Hacer que la etiqueta sea de solo lectura
Section titled “Hacer que la etiqueta sea de solo lectura”await CapacitorNfc.makeReadOnly();console.log('Tag is now read-only');Detener escaneo
Section titled “Detener escaneo”await listener.remove();await CapacitorNfc.stopScanning();Verificar estado de NFC
Section titled “Verificar estado de NFC”const { status } = await CapacitorNfc.getStatus();console.log('NFC status:', status);// Possible values: 'NFC_OK', 'NO_NFC', 'NFC_DISABLED', 'NDEF_PUSH_DISABLED'
if (status === 'NFC_DISABLED') { // Open system settings await CapacitorNfc.showSettings();}Android Haz (compartir P2P)
Section titled “Android Haz (compartir P2P)”// Share data via Android Beamconst message = { records: [ { tnf: 0x01, type: [0x54], // Text id: [], payload: [/* text record payload */], }, ],};
await CapacitorNfc.share(message);
// Later, stop sharingawait CapacitorNfc.unshare();API Referencia
Section titled “API Referencia”iniciar escaneo (¿opciones?)
Section titled “iniciar escaneo (¿opciones?)”Empiece a escuchar las etiquetas NFC.
interface StartScanningOptions { invalidateAfterFirstRead?: boolean; // iOS only, defaults to true alertMessage?: string; // iOS only androidReaderModeFlags?: number; // Android only}
await CapacitorNfc.startScanning(options);detener el escaneo()
Section titled “detener el escaneo()”Detenga la sesión de escaneo NFC.
await CapacitorNfc.stopScanning();escribir (opciones)
Section titled “escribir (opciones)”Escriba registros NDEF en la última etiqueta descubierta.
interface WriteTagOptions { records: NdefRecord[]; allowFormat?: boolean; // Defaults to true}
interface NdefRecord { tnf: number; // Type Name Format type: number[]; // Record type id: number[]; // Record ID payload: number[]; // Record payload}
await CapacitorNfc.write(options);borrar()
Section titled “borrar()”Borre la última etiqueta descubierta.
await CapacitorNfc.erase();hacerSoloLectura()
Section titled “hacerSoloLectura()”Haga que la última etiqueta descubierta sea de solo lectura (permanente).
await CapacitorNfc.makeReadOnly();compartir (opciones)
Section titled “compartir (opciones)”Comparta el mensaje NDEF a través de Android Beam (solo Android).
await CapacitorNfc.share({ records: [...] });dejar de compartir()
Section titled “dejar de compartir()”Dejar de compartir (solo Android).
await CapacitorNfc.unshare();obtener estado()
Section titled “obtener estado()”Obtenga el estado actual del adaptador NFC.
const { status } = await CapacitorNfc.getStatus();// Returns: 'NFC_OK' | 'NO_NFC' | 'NFC_DISABLED' | 'NDEF_PUSH_DISABLED'mostrar configuración()
Section titled “mostrar configuración()”Abra la configuración NFC del sistema.
await CapacitorNfc.showSettings();Eventos
Section titled “Eventos”evento nfc
Section titled “evento nfc”Se activa cuando se descubre una etiqueta NFC.
interface NfcEvent { type: 'tag' | 'ndef' | 'ndef-mime' | 'ndef-formattable'; tag?: NfcTag;}
interface NfcTag { id: number[]; techTypes: string[]; type: string | null; maxSize: number | null; isWritable: boolean | null; canMakeReadOnly: boolean | null; ndefMessage: NdefRecord[] | null;}cambio de estado nfc
Section titled “cambio de estado nfc”Se activa cuando cambia la disponibilidad del adaptador NFC (solo Android).
interface NfcStateChangeEvent { status: NfcStatus; enabled: boolean;}Ejemplo completo
Section titled “Ejemplo completo”import { CapacitorNfc } from '@capgo/capacitor-nfc';
export class NfcService { private listener: any;
async startReading() { // Check NFC status const { status } = await CapacitorNfc.getStatus();
if (status === 'NO_NFC') { throw new Error('NFC not available on this device'); }
if (status === 'NFC_DISABLED') { await CapacitorNfc.showSettings(); return; }
// Start scanning await CapacitorNfc.startScanning({ invalidateAfterFirstRead: false, alertMessage: 'Ready to scan NFC tags', });
// Listen for tags this.listener = await CapacitorNfc.addListener('nfcEvent', (event) => { this.handleNfcEvent(event); }); }
private handleNfcEvent(event: any) { console.log('NFC Event:', event.type);
if (event.tag?.ndefMessage) { event.tag.ndefMessage.forEach(record => { this.processRecord(record); }); } }
private processRecord(record: any) { // Process text records if (record.tnf === 1 && record.type[0] === 0x54) { const langLen = record.payload[0] & 0x3f; const text = new TextDecoder().decode( new Uint8Array(record.payload.slice(langLen + 1)) ); console.log('Text:', text); }
// Process URI records if (record.tnf === 1 && record.type[0] === 0x55) { const uriCode = record.payload[0]; const uri = new TextDecoder().decode( new Uint8Array(record.payload.slice(1)) ); console.log('URI:', uri); } }
async writeText(text: string) { const encoder = new TextEncoder(); const langBytes = Array.from(encoder.encode('en')); const textBytes = Array.from(encoder.encode(text)); const payload = [langBytes.length & 0x3f, ...langBytes, ...textBytes];
await CapacitorNfc.write({ allowFormat: true, records: [ { tnf: 0x01, type: [0x54], id: [], payload, }, ], }); }
async stopReading() { if (this.listener) { await this.listener.remove(); } await CapacitorNfc.stopScanning(); }}Tipos de registros NDEF
Section titled “Tipos de registros NDEF”TNF (formato de nombre de tipo)
Section titled “TNF (formato de nombre de tipo)”0x00: Vacío0x01: conocido (p. ej., texto, URI)0x02: tipo de medio MIME0x03: URI absoluta0x04: tipo externo0x05: Desconocido0x06: Sin cambios0x07: Reservado
Tipos de registros comunes
Section titled “Tipos de registros comunes”- Texto:
type: [0x54](‘T’) - URI:
type: [0x55](‘U’) - Póster inteligente:
type: [0x53, 0x70](‘Sp’)
Prefijos URI
Section titled “Prefijos URI”0x00: (sin prefijo)0x01:https://0x02:https://0x03:http://0x04:https://www.
Mejores prácticas
Section titled “Mejores prácticas”- Verificar estado de NFC: Verifique siempre que NFC esté disponible y habilitado
- Manejar permisos: solicite permisos NFC de forma adecuada
- Detener escaneo: Detenga siempre el escaneo cuando haya terminado para ahorrar batería
- Manejo de errores: envuelva las operaciones NFC en bloques try-catch
- Prueba en dispositivos: las funciones NFC no funcionan en simuladores/emuladores
Notas de plataforma
Section titled “Notas de plataforma”- Requiere iOS 11.0+
- Utiliza el marco Core NFC
- Admite lectura de etiquetas en segundo plano (iOS 13+)
- Limitado a leer etiquetas con formato NDEF
- No se pueden escribir etiquetas en segundo plano.
- Requiere NFCReaderUsageDescription en Info.plist### Android
- Requiere Android 4.4 (API 19)+
- Utiliza Android NFC API
- Admite lectura de etiquetas tanto en primer plano como en segundo plano
- Puede escribir en etiquetas
- Admite Android Beam (P2P) en dispositivos con NFC
- Requiere permiso NFC en AndroidManifest.xml
- No compatible con la plataforma web