Saltar al contenido

Primeros pasos

GitHub

Puedes usar nuestro setup asistido por IA para instalar el plugin. Añade las skills de Capgo a tu herramienta de IA con el siguiente comando:

Ventana de terminal
bunx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins

Luego usa el siguiente prompt:

Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-nfc` plugin in my project.

Si prefieres la configuración manual, instala el plugin ejecutando estos comandos y sigue las instrucciones de cada plataforma:

Ventana de terminal
bun add @capgo/capacitor-nfc
bunx cap sync
import { CapacitorNfc } from '@capgo/capacitor-nfc';
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.startScanning();
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.stopScanning();
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.write({
records: [
{
tnf: 1,
type: [1],
id: [1],
payload: [1],
},
],
});
  • Listeners: elimina los handles cuando se desmonten las pantallas.
  • Sync nativo: ejecuta bunx cap sync tras actualizar los plugins.
  • Fuente de verdad: confianza src/definitions.ts en el repo de GitHub.

Comienza a escuchar etiquetas NFC.

import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.startScanning();

Detiene la sesión de escaneo NFC en curso.

import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.stopScanning();

Escribe los registros NDEF proporcionados en la última etiqueta detectada.

import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.write({
records: [
{
tnf: 1,
type: [1],
id: [1],
payload: [1],
},
],
});

Intenta borrar la última etiqueta detectada escribiendo un mensaje NDEF vacío.

import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.erase();

Intenta poner la última etiqueta detectada en modo de solo lectura.

import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.makeReadOnly();

Comparte un mensaje NDEF con otro dispositivo vía peer-to-peer (solo Android).

import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.share({
records: [
{
tnf: 1,
type: [1],
id: [1],
payload: [1],
},
],
});

Deja de compartir el mensaje NDEF proporcionado anteriormente (solo Android).

import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.unshare();

Devuelve el estado actual del adaptador NFC.

import { CapacitorNfc } from '@capgo/capacitor-nfc';
const result = await CapacitorNfc.getStatus();
console.log(result);

Abre la página de ajustes del sistema donde el usuario puede activar el NFC.

import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.showSettings();

Comprueba si el dispositivo tiene soporte de hardware NFC.

Devuelve true si el dispositivo cuenta con hardware NFC, independientemente de si NFC está actualmente activado o desactivado. Devuelve false si el dispositivo no tiene hardware NFC.

Usa este método para determinar si las funciones de NFC deben mostrarse en la interfaz de tu app. Para verificar si NFC está actualmente activado, usa getStatus().

import { CapacitorNfc } from '@capgo/capacitor-nfc';
const result = await CapacitorNfc.isSupported();
console.log(result);

Opciones que controlan el comportamiento de .

export interface StartScanningOptions {
/**
* iOS-only: closes the NFC session automatically after the first successful tag read.
* Defaults to `true`.
*/
invalidateAfterFirstRead?: boolean;
/**
* iOS-only: custom message displayed in the NFC system sheet while scanning.
*/
alertMessage?: string;
/**
* iOS-only: session type to use for NFC scanning.
* - `'ndef'`: Uses NFCNDEFReaderSession (default). Only detects NDEF-formatted tags.
* - `'tag'`: Uses NFCTagReaderSession. Detects both NDEF and non-NDEF tags (e.g., raw MIFARE tags).
* Allows reading UID from unformatted tags.
* **Requires** the `Near Field Communication Tag Reader Session Formats` entitlement
* in your app with the `TAG` format included. Without it the session will fail to
* start and the promise will reject with a `NO_NFC` error code.
* Defaults to `'ndef'` for backward compatibility.
*/
iosSessionType?: 'ndef' | 'tag';
/**
* Android-only: raw flags passed to `NfcAdapter.enableReaderMode`.
* Defaults to enabling all tag types with skipping NDEF checks.
*/
androidReaderModeFlags?: number;
}

Opciones para escribir un mensaje NDEF en el tag actual.

export interface WriteTagOptions {
/**
* Array of records that compose the NDEF message to be written.
*/
records: NdefRecord[];
/**
* When `true`, the plugin attempts to format NDEF-formattable tags before writing.
* Defaults to `true`.
*/
allowFormat?: boolean;
}

Opciones para compartir un mensaje NDEF con otro dispositivo mediante Android Beam / modo P2P.

export interface ShareTagOptions {
records: NdefRecord[];
}

Posibles estados del adaptador NFC devueltos por .

export type NfcStatus = 'NFC_OK' | 'NO_NFC' | 'NFC_DISABLED' | 'NDEF_PUSH_DISABLED';

Evento de detección NFC genérico emitido por el plugin.

export interface NfcEvent {
type: NfcEventType;
tag: NfcTag;
}

Evento emitido cada vez que cambia la disponibilidad del adaptador NFC.

export interface NfcStateChangeEvent {
status: NfcStatus;
enabled: boolean;
}

Estructura JSON que representa un registro NDEF individual.

export interface NdefRecord {
/**
* Type Name Format identifier.
*/
tnf: number;
/**
* Type field expressed as an array of byte values.
*/
type: number[];
/**
* Record identifier expressed as an array of byte values.
*/
id: number[];
/**
* Raw payload expressed as an array of byte values.
*/
payload: number[];
}

Tipo de evento que describe el tipo de detección de NFC que se produjo.

export type NfcEventType = 'tag' | 'ndef' | 'ndef-mime' | 'ndef-formatable';

Representación de toda la información de la etiqueta devuelta por las capas nativas.

export interface NfcTag {
/**
* Raw identifier bytes for the tag.
*/
id?: number[];
/**
* List of Android tech strings (e.g. `android.nfc.tech.Ndef`).
*/
techTypes?: string[];
/**
* Human readable tag type when available (e.g. `NFC Forum Type 2`, `MIFARE Ultralight`).
*/
type?: string | null;
/**
* Maximum writable size in bytes for tags that expose NDEF information.
*/
maxSize?: number | null;
/**
* Indicates whether the tag can be written to.
*/
isWritable?: boolean | null;
/**
* Indicates whether the tag can be permanently locked.
*/
canMakeReadOnly?: boolean | null;
/**
* Array of NDEF records discovered on the tag.
*/
ndefMessage?: NdefRecord[] | null;
}

Esta página se genera a partir del plugin src/definitions.ts. Vuelve a ejecutar el sync cuando el API público cambie en upstream.

Si estás usando Primeros pasos para planificar las operaciones del dashboard y de API, conéctalo con Usando @capgo/capacitor-nfc para la capacidad nativa en Uso de @capgo/capacitor-nfc, Resumen de API para los detalles de implementación en API Overview, Introducción para los detalles de implementación en la Introducción, Claves de API para los detalles de implementación en las claves de API, y Dispositivos para el detalle de implementación en Devices.