Primeros pasos
Copia un prompt de configuración con los pasos de instalación y la guía completa en markdown para este plugin.
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-nfc`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/nfc/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
Instalar
Sección titulada “Instalación”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:
bunx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsLuego 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 los siguientes comandos y sigue las instrucciones específicas para cada plataforma a continuación:
bun add @capgo/capacitor-nfcbunx cap syncImportar
Sección titulada “Importar”import { CapacitorNfc } from '@capgo/capacitor-nfc';Quick start
Sección titulada “Guía de inicio rápido”import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.startScanning();Ejemplo: stopScanning
Sección titulada “Ejemplo: stopScanning”import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.stopScanning();Ejemplo: write
Sección titulada “Ejemplo: write”import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.write({ records: [ { tnf: 1, type: [1], id: [1], payload: [1], }, ],});Errores comunes
Sección titulada “Errores comunes”- Listeners: elimina los handles al desmontar pantallas.
- Native sync: ejecutar
bunx cap synctras actualizar el plugin. - Fuente de verdad: confiar
src/definitions.tsen el repo de GitHub.
Resumen de API
Sección titulada “Resumen de API”startScanning
Sección titulada “startScanning”Empieza a escuchar etiquetas NFC.
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.startScanning();stopScanning
Sección titulada “stopScanning”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();makeReadOnly
Sección titulada “makeReadOnly”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 mediante peer-to-peer (solo Android).
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.share({ records: [ { tnf: 1, type: [1], id: [1], payload: [1], }, ],});unshare
Sección titulada “unshare”Deja de compartir el mensaje NDEF proporcionado anteriormente (solo Android).
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.unshare();getStatus
Sección titulada “getStatus”Devuelve el estado actual del adaptador NFC.
import { CapacitorNfc } from '@capgo/capacitor-nfc';
const result = await CapacitorNfc.getStatus();console.log(result);showSettings
Sección titulada “showSettings”Abre la página de ajustes del sistema para que el usuario active el NFC.
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.showSettings();isSupported
Sección titulada “isSupported”Comprueba si el dispositivo tiene soporte de hardware NFC.
Devuelve true si el hardware NFC está presente en el dispositivo, independientemente de
que el NFC esté activado o desactivado. Devuelve false si el
dispositivo no tiene hardware NFC.
Usa este método para determinar si debes mostrar funciones NFC en la
interfaz de tu app. Para saber si el NFC está activado, usa getStatus().
import { CapacitorNfc } from '@capgo/capacitor-nfc';
const result = await CapacitorNfc.isSupported();console.log(result);Referencia de tipos
Sección titulada “Referencia de tipos”StartScanningOptions
Sección titulada “StartScanningOptions”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;}WriteTagOptions
Sección titulada “WriteTagOptions”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;}ShareTagOptions
Sección titulada “ShareTagOptions”Opciones para compartir un mensaje NDEF con otro dispositivo mediante Android Beam / modo P2P.
export interface ShareTagOptions { records: NdefRecord[];}NfcStatus
Sección titulada “NfcStatus”Posibles estados del adaptador NFC devueltos por .
export type NfcStatus = 'NFC_OK' | 'NO_NFC' | 'NFC_DISABLED' | 'NDEF_PUSH_DISABLED';NfcEvent
Sección titulada “NfcEvent”Evento genérico de descubrimiento NFC enviado por el plugin.
export interface NfcEvent { type: NfcEventType; tag: NfcTag;}NfcStateChangeEvent
Sección titulada “NfcStateChangeEvent”Evento emitido cuando cambia la disponibilidad del adaptador NFC.
export interface NfcStateChangeEvent { status: NfcStatus; enabled: boolean;}NdefRecord
Sección titulada “NdefRecord”Estructura JSON que representa un único registro NDEF.
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[];}NfcEventType
Sección titulada “NfcEventType”Tipo de evento que describe el tipo de descubrimiento NFC ocurrido.
export type NfcEventType = 'tag' | 'ndef' | 'ndef-mime' | 'ndef-formatable';Representación de la información completa del tag 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;}Fuente de verdad
Sección titulada “Fuente de verdad”Esta página se genera desde el src/definitions.ts. Ejecuta el sync de nuevo cuando el API público cambie en el upstream.
Continúa desde Primeros pasos
Sección titulada “Continúa desde Primeros pasos”Si estás usando Primeros pasos para planificar el dashboard y las operaciones de API, conéctalo con Usando @capgo/capacitor-nfc para la capacidad nativa en Usando @capgo/capacitor-nfc, Resumen de API para los detalles de implementación en el Overview de API, Introducción para los detalles de implementación en la Introducción, Claves de API para los detalles de implementación en las Keys de API, y Dispositivos para los detalles de implementación en Dispositivos.