Erste Schritte
-
Paket installieren
Terminal-Fenster npm i @capgo/capacitor-nfcTerminal-Fenster pnpm add @capgo/capacitor-nfcTerminal-Fenster yarn add @capgo/capacitor-nfcTerminal-Fenster bun add @capgo/capacitor-nfc -
Mit nativen Projekten synchronisieren
Terminal-Fenster npx cap syncTerminal-Fenster pnpm cap syncTerminal-Fenster yarn cap syncTerminal-Fenster bunx cap sync
Konfiguration
Section titled “Konfiguration”iOS-Konfiguration
Section titled “iOS-Konfiguration”Fügen Sie die NFC-Verwendungsbeschreibung zu Ihrer Info.plist hinzu:
<key>NFCReaderUsageDescription</key><string>Diese App benötigt NFC-Zugriff zum Lesen und Schreiben von Tags</string>Aktivieren Sie die Near Field Communication Tag Reading-Funktion in Ihrem Xcode-Projekt.
Android-Konfiguration
Section titled “Android-Konfiguration”Fügen Sie die NFC-Berechtigung zu Ihrer AndroidManifest.xml hinzu:
<manifest> <uses-permission android:name="android.permission.NFC" /> <uses-feature android:name="android.hardware.nfc" android:required="false" /></manifest>Verwendung
Section titled “Verwendung”Scannen nach NFC-Tags starten
Section titled “Scannen nach NFC-Tags starten”import { CapacitorNfc } from '@capgo/capacitor-nfc';
await CapacitorNfc.startScanning({ invalidateAfterFirstRead: false, // Sitzung offen halten (iOS) alertMessage: 'Halten Sie ein Tag in die Nähe Ihres Geräts.',});
const listener = await CapacitorNfc.addListener('nfcEvent', (event) => { console.log('Tag erkannt:', event.type); console.log('Tag-ID:', event.tag?.id); console.log('NDEF-Nachricht:', event.tag?.ndefMessage);});NFC-Tag lesen
Section titled “NFC-Tag lesen”await CapacitorNfc.addListener('nfcEvent', (event) => { if (event.tag?.ndefMessage) { event.tag.ndefMessage.forEach(record => { console.log('TNF:', record.tnf); console.log('Typ:', record.type); console.log('Payload:', record.payload);
// Text-Datensatz dekodieren if (record.tnf === 1 && record.type[0] === 0x54) { // Text-Datensatz const langLen = record.payload[0] & 0x3f; const text = new TextDecoder().decode( new Uint8Array(record.payload.slice(langLen + 1)) ); console.log('Text:', text); } }); }});Auf NFC-Tag schreiben
Section titled “Auf NFC-Tag schreiben”// Text-Datensatz vorbereitenconst 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' für Text id: [], payload, }, ],});
console.log('Tag erfolgreich geschrieben');URL auf NFC-Tag schreiben
Section titled “URL auf NFC-Tag schreiben”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' für URI id: [], payload: [0x01, ...urlBytes], // 0x01 = https:// }, ],});NFC-Tag löschen
Section titled “NFC-Tag löschen”await CapacitorNfc.erase();console.log('Tag gelöscht');Tag schreibgeschützt machen
Section titled “Tag schreibgeschützt machen”await CapacitorNfc.makeReadOnly();console.log('Tag ist jetzt schreibgeschützt');Scannen stoppen
Section titled “Scannen stoppen”await listener.remove();await CapacitorNfc.stopScanning();NFC-Status prüfen
Section titled “NFC-Status prüfen”const { status } = await CapacitorNfc.getStatus();console.log('NFC-Status:', status);// Mögliche Werte: 'NFC_OK', 'NO_NFC', 'NFC_DISABLED', 'NDEF_PUSH_DISABLED'
if (status === 'NFC_DISABLED') { // Systemeinstellungen öffnen await CapacitorNfc.showSettings();}Android Beam (P2P-Freigabe)
Section titled “Android Beam (P2P-Freigabe)”// Daten über Android Beam teilenconst message = { records: [ { tnf: 0x01, type: [0x54], // Text id: [], payload: [/* Text-Datensatz-Payload */], }, ],};
await CapacitorNfc.share(message);
// Später Freigabe beendenawait CapacitorNfc.unshare();API-Referenz
Section titled “API-Referenz”startScanning(options?)
Section titled “startScanning(options?)”Beginnen Sie, auf NFC-Tags zu lauschen.
interface StartScanningOptions { invalidateAfterFirstRead?: boolean; // Nur iOS, Standard ist true alertMessage?: string; // Nur iOS androidReaderModeFlags?: number; // Nur Android}
await CapacitorNfc.startScanning(options);stopScanning()
Section titled “stopScanning()”Stoppen Sie die NFC-Scansitzung.
await CapacitorNfc.stopScanning();write(options)
Section titled “write(options)”Schreiben Sie NDEF-Datensätze auf das zuletzt erkannte Tag.
interface WriteTagOptions { records: NdefRecord[]; allowFormat?: boolean; // Standard ist true}
interface NdefRecord { tnf: number; // Type Name Format type: number[]; // Datensatztyp id: number[]; // Datensatz-ID payload: number[]; // Datensatz-Payload}
await CapacitorNfc.write(options);erase()
Section titled “erase()”Löschen Sie das zuletzt erkannte Tag.
await CapacitorNfc.erase();makeReadOnly()
Section titled “makeReadOnly()”Machen Sie das zuletzt erkannte Tag schreibgeschützt (permanent).
await CapacitorNfc.makeReadOnly();share(options)
Section titled “share(options)”Teilen Sie NDEF-Nachricht über Android Beam (nur Android).
await CapacitorNfc.share({ records: [...] });unshare()
Section titled “unshare()”Freigabe stoppen (nur Android).
await CapacitorNfc.unshare();getStatus()
Section titled “getStatus()”Aktuellen NFC-Adapterstatus abrufen.
const { status } = await CapacitorNfc.getStatus();// Gibt zurück: 'NFC_OK' | 'NO_NFC' | 'NFC_DISABLED' | 'NDEF_PUSH_DISABLED'showSettings()
Section titled “showSettings()”System-NFC-Einstellungen öffnen.
await CapacitorNfc.showSettings();Events
Section titled “Events”nfcEvent
Section titled “nfcEvent”Wird ausgelöst, wenn ein NFC-Tag erkannt wird.
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;}nfcStateChange
Section titled “nfcStateChange”Wird ausgelöst, wenn sich die NFC-Adapterverfügbarkeit ändert (nur Android).
interface NfcStateChangeEvent { status: NfcStatus; enabled: boolean;}Vollständiges Beispiel
Section titled “Vollständiges Beispiel”import { CapacitorNfc } from '@capgo/capacitor-nfc';
export class NfcService { private listener: any;
async startReading() { // NFC-Status prüfen const { status } = await CapacitorNfc.getStatus();
if (status === 'NO_NFC') { throw new Error('NFC auf diesem Gerät nicht verfügbar'); }
if (status === 'NFC_DISABLED') { await CapacitorNfc.showSettings(); return; }
// Scannen starten await CapacitorNfc.startScanning({ invalidateAfterFirstRead: false, alertMessage: 'Bereit zum Scannen von NFC-Tags', });
// Auf Tags lauschen 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) { // Text-Datensätze verarbeiten 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); }
// URI-Datensätze verarbeiten 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(); }}NDEF-Datensatztypen
Section titled “NDEF-Datensatztypen”TNF (Type Name Format)
Section titled “TNF (Type Name Format)”0x00: Leer0x01: Well-known (z. B. Text, URI)0x02: MIME-Medientyp0x03: Absolute URI0x04: Externer Typ0x05: Unbekannt0x06: Unverändert0x07: Reserviert
Gängige Datensatztypen
Section titled “Gängige Datensatztypen”- Text:
type: [0x54](‘T’) - URI:
type: [0x55](‘U’) - Smart Poster:
type: [0x53, 0x70](‘Sp’)
URI-Präfixe
Section titled “URI-Präfixe”0x00: (kein Präfix)0x01:https://0x02:https://0x03:http://0x04:https://www.
Best Practices
Section titled “Best Practices”- NFC-Status prüfen: Überprüfen Sie immer, ob NFC verfügbar und aktiviert ist
- Berechtigungen handhaben: Fordern Sie NFC-Berechtigungen entsprechend an
- Scannen stoppen: Stoppen Sie das Scannen immer, wenn Sie fertig sind, um Akku zu sparen
- Fehlerbehandlung: Umschließen Sie NFC-Operationen mit try-catch-Blöcken
- Auf Geräten testen: NFC-Funktionen funktionieren nicht auf Simulatoren/Emulatoren
Plattformhinweise
Section titled “Plattformhinweise”- Erfordert iOS 11.0+
- Verwendet Core NFC Framework
- Unterstützt Hintergrund-Tag-Lesen (iOS 13+)
- Beschränkt auf das Lesen von NDEF-formatierten Tags
- Kann Tags nicht im Hintergrund schreiben
- Erfordert NFCReaderUsageDescription in Info.plist
Android
Section titled “Android”- Erfordert Android 4.4 (API 19)+
- Verwendet Android NFC API
- Unterstützt sowohl Vordergrund- als auch Hintergrund-Tag-Lesen
- Kann auf Tags schreiben
- Unterstützt Android Beam (P2P) auf Geräten mit NFC
- Erfordert NFC-Berechtigung in AndroidManifest.xml
- Auf Web-Plattform nicht unterstützt