Getting Started
Copiar un prompt de configuración con los pasos de instalación y la guía de markdown completa 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 “Instalar”Puede utilizar nuestra configuración asistida por IA para instalar el plugin. Agregue las Capgo habilidades a su herramienta de IA utilizando el siguiente comando:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-pluginsUsa luego la siguiente solicitud:
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 complemento ejecutando los siguientes comandos y sigue las instrucciones específicas de la plataforma a continuación:
bun add @capgo/capacitor-nfcbunx cap syncImportar
Título de la sección “Importar”import { CapacitorNfc } from '@capgo/capacitor-nfc';API Resumen
Título de la sección “API Resumen”startScanning
Título de la sección “startScanning”Comienza a escuchar etiquetas NFC.
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.startScanning();stopScanning
Sección titulada “detener la escaneo”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 descubierta.
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.write({ records: [ { tnf: 1, type: [1], id: [1], payload: [1], }, ],});Intenta borrar la última etiqueta descubierta escribiendo un mensaje NDEF vacío.
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.erase();makeReadOnly
Sección titulada “hacerlo de solo lectura”Intenta hacer la última etiqueta descubierta de solo lectura.
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.makeReadOnly();Comparte un mensaje NDEF con otro dispositivo mediante p2p (solo para Android).
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.share({ records: [ { tnf: 1, type: [1], id: [1], payload: [1], }, ],});Detiene la compartición del mensaje NDEF proporcionado anteriormente (solo para Android).
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.unshare();getStatus
Sección titulada “obtenerEstado”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 “mostrarConfiguración”Abre la página de configuración del sistema donde el usuario puede habilitar el NFC.
import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.showSettings();isSupported
Título de la sección “isSupported”Verifica si el dispositivo tiene soporte de hardware NFC.
Devuelve true si el hardware NFC está presente en el dispositivo, sin importar si NFC está actualmente habilitado o deshabilitado. false si el dispositivo no tiene hardware NFC.
Utilice este método para determinar si se deben mostrar características NFC en la interfaz de usuario de su aplicación. Para verificar si NFC está actualmente habilitado, utilice getStatus().
import { CapacitorNfc } from '@capgo/capacitor-nfc';
const result = await CapacitorNfc.isSupported();console.log(result);Referencia de tipo
Título de la sección “Type Reference”StartScanningOptions
Título de la sección “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 utilizadas cuando se escribe un mensaje NDEF en la etiqueta 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 utilizadas cuando se comparte un mensaje NDEF con otro dispositivo utilizando el modo Android Beam / 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 de descubrimiento NFC genérico emitido por el plugin.
export interface NfcEvent { type: NfcEventType; tag: NfcTag;}NfcStateChangeEvent
Título de la sección “NfcStateChangeEvent”Evento emitido cada vez que cambia la disponibilidad del adaptador NFC.
export interface NfcStateChangeEvent { status: NfcStatus; enabled: boolean;}NdefRecord
Título de la sección “NdefRecord”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[];}NfcEventType
Título de la sección “NfcEventType”Tipo de evento que describe el tipo de descubrimiento NFC que ocurrió.
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;}Fuente de Verdad
Sección titulada “Fuente de Verdad”Esta página se genera a partir de la extensión’s src/definitions.ts. Vuelva a sincronizar cuando los cambios públicos API cambien en la fuente.
Siga adelante desde Inicio
Sección titulada “Siga adelante desde Inicio”Si está utilizando Getting Started para planificar la consola y API operaciones, conecte con Usando @capgo/capacitor-nfc para la capacidad nativa en Usando @capgo/capacitor-nfc, API Overview Para los detalles de implementación en API Resumen Introducción para los detalles de implementación en la Introducción. Claves de API para los detalles de implementación en las API Claves. Dispositivos Para los detalles de implementación en dispositivos.