Nfc
Read and write NDEF tags with the Web NFC API - scan for nearby tags, then write text or URL records to the next tag the user taps.
@inject Bit.Butil.Nfc nfcMDN reference
IsSupported first and keep every call inside a try/catch.
nfc permission prompt. Scanning and writing must be initiated from a user
gesture such as a button click.
Returns true when the runtime exposes NDEFReader. During prerender/SSR the check returns false rather than throwing, so defer it to OnAfterRenderAsync.
@inject Bit.Butil.Nfc nfc
var supported = await nfc.IsSupported();Starts listening for NDEF tags. Each tap delivers a typed NdefMessage - the tag's serial number plus its records (record type, MIME type, language, decoded text or raw bytes). Dispose the returned handle to stop scanning.
private IAsyncDisposable? _scan;
_scan = await nfc.Scan(
onReading: message =>
{
var serial = message.SerialNumber;
foreach (var record in message.Records)
{
// record.RecordType: "text", "url", "mime", ...
// record.Text: decoded payload for text records
}
},
onError: error => { /* scan/read error message */ });
// stop scanning:
await _scan.DisposeAsync();Writes a single NDEF text record to the next tag tapped against the device. The optional lang parameter sets the record's BCP-47 language tag; the optional id sets an application-defined record id.
var ok = await nfc.WriteText("Hello from Butil!", lang: "en");
// ok == true when the record was written to the tapped tagWrites a single NDEF URL record to the next tag tapped against the device - a tag that most phones will open in the browser when scanned.
var ok = await nfc.WriteUrl("https://bitplatform.dev");API reference
ValueTask<bool> IsSupported()Task<IAsyncDisposable> Scan(Action<NdefMessage>? onReading, Action<string>? onError = null)ValueTask<bool> WriteText(string text, string? lang = null, string? id = null)ValueTask<bool> WriteUrl(string url, string? id = null)ValueTask DisposeAsync()void InvokeNdefReading(Guid id, NdefMessage message)void InvokeNdefError(Guid id, string message)string SerialNumber { get; set; }NdefRecord[] Records { get; set; }