Saltar al contenido

Empezando

  1. Instalar el paquete

    Ventana de terminal
    npm i @capgo/capacitor-nfc
  2. Sincronización con proyectos nativos

    Ventana de terminal
    npx cap sync

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.

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);
});
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);
}
});
}
});
// Prepare a text record
const 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');
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://
},
],
});
await CapacitorNfc.erase();
console.log('Tag erased');
await CapacitorNfc.makeReadOnly();
console.log('Tag is now read-only');
await listener.remove();
await CapacitorNfc.stopScanning();
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();
}
// Share data via Android Beam
const message = {
records: [
{
tnf: 0x01,
type: [0x54], // Text
id: [],
payload: [/* text record payload */],
},
],
};
await CapacitorNfc.share(message);
// Later, stop sharing
await CapacitorNfc.unshare();

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);

Detenga la sesión de escaneo NFC.

await CapacitorNfc.stopScanning();

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);

Borre la última etiqueta descubierta.

await CapacitorNfc.erase();

Haga que la última etiqueta descubierta sea de solo lectura (permanente).

await CapacitorNfc.makeReadOnly();

Comparta el mensaje NDEF a través de Android Beam (solo Android).

await CapacitorNfc.share({ records: [...] });

Dejar de compartir (solo Android).

await CapacitorNfc.unshare();

Obtenga el estado actual del adaptador NFC.

const { status } = await CapacitorNfc.getStatus();
// Returns: 'NFC_OK' | 'NO_NFC' | 'NFC_DISABLED' | 'NDEF_PUSH_DISABLED'

Abra la configuración NFC del sistema.

await CapacitorNfc.showSettings();

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;
}

Se activa cuando cambia la disponibilidad del adaptador NFC (solo Android).

interface NfcStateChangeEvent {
status: NfcStatus;
enabled: boolean;
}
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();
}
}
  • 0x00: Vacío
  • 0x01: conocido (p. ej., texto, URI)
  • 0x02: tipo de medio MIME
  • 0x03: URI absoluta
  • 0x04: tipo externo
  • 0x05: Desconocido
  • 0x06: Sin cambios
  • 0x07: Reservado
  • Texto: type: [0x54] (‘T’)
  • URI: type: [0x55] (‘U’)
  • Póster inteligente: type: [0x53, 0x70] (‘Sp’)
  • 0x00: (sin prefijo)
  • 0x01: https://
  • 0x02: https://
  • 0x03: http://
  • 0x04: https://www.
  1. Verificar estado de NFC: Verifique siempre que NFC esté disponible y habilitado
  2. Manejar permisos: solicite permisos NFC de forma adecuada
  3. Detener escaneo: Detenga siempre el escaneo cuando haya terminado para ahorrar batería
  4. Manejo de errores: envuelva las operaciones NFC en bloques try-catch
  5. Prueba en dispositivos: las funciones NFC no funcionan en simuladores/emuladores
  • 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