Zum Inhalt springen

Erste Schritte

  1. Paket installieren

    Terminal-Fenster
    npm i @capgo/capacitor-nfc
  2. Mit nativen Projekten synchronisieren

    Terminal-Fenster
    npx cap sync

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.

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>
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);
});
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);
}
});
}
});
// Text-Datensatz vorbereiten
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' für Text
id: [],
payload,
},
],
});
console.log('Tag erfolgreich geschrieben');
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://
},
],
});
await CapacitorNfc.erase();
console.log('Tag gelöscht');
await CapacitorNfc.makeReadOnly();
console.log('Tag ist jetzt schreibgeschützt');
await listener.remove();
await CapacitorNfc.stopScanning();
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();
}
// Daten über Android Beam teilen
const message = {
records: [
{
tnf: 0x01,
type: [0x54], // Text
id: [],
payload: [/* Text-Datensatz-Payload */],
},
],
};
await CapacitorNfc.share(message);
// Später Freigabe beenden
await CapacitorNfc.unshare();

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

Stoppen Sie die NFC-Scansitzung.

await CapacitorNfc.stopScanning();

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

Löschen Sie das zuletzt erkannte Tag.

await CapacitorNfc.erase();

Machen Sie das zuletzt erkannte Tag schreibgeschützt (permanent).

await CapacitorNfc.makeReadOnly();

Teilen Sie NDEF-Nachricht über Android Beam (nur Android).

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

Freigabe stoppen (nur Android).

await CapacitorNfc.unshare();

Aktuellen NFC-Adapterstatus abrufen.

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

System-NFC-Einstellungen öffnen.

await CapacitorNfc.showSettings();

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

Wird ausgelöst, wenn sich die NFC-Adapterverfügbarkeit ändert (nur Android).

interface NfcStateChangeEvent {
status: NfcStatus;
enabled: boolean;
}
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();
}
}
  • 0x00: Leer
  • 0x01: Well-known (z. B. Text, URI)
  • 0x02: MIME-Medientyp
  • 0x03: Absolute URI
  • 0x04: Externer Typ
  • 0x05: Unbekannt
  • 0x06: Unverändert
  • 0x07: Reserviert
  • Text: type: [0x54] (‘T’)
  • URI: type: [0x55] (‘U’)
  • Smart Poster: type: [0x53, 0x70] (‘Sp’)
  • 0x00: (kein Präfix)
  • 0x01: https://
  • 0x02: https://
  • 0x03: http://
  • 0x04: https://www.
  1. NFC-Status prüfen: Überprüfen Sie immer, ob NFC verfügbar und aktiviert ist
  2. Berechtigungen handhaben: Fordern Sie NFC-Berechtigungen entsprechend an
  3. Scannen stoppen: Stoppen Sie das Scannen immer, wenn Sie fertig sind, um Akku zu sparen
  4. Fehlerbehandlung: Umschließen Sie NFC-Operationen mit try-catch-Blöcken
  5. Auf Geräten testen: NFC-Funktionen funktionieren nicht auf Simulatoren/Emulatoren
  • 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
  • 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