Skip to main content

tauri_plugin_nfc/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Read and write NFC tags on Android and iOS.
6//!
7//! This plugin is mobile only: the whole crate is gated behind `#[cfg(mobile)]`,
8//! so it expands to nothing when compiling for Linux, macOS or Windows.
9//!
10//! Register the plugin with `init` and use the `NfcExt` trait to reach the
11//! `Nfc` instance from any `tauri::Manager` implementation (the app handle, a window, ...).
12
13#![cfg(mobile)]
14
15use serde::{Deserialize, Serialize};
16use tauri::{
17    Manager, Runtime,
18    plugin::{Builder, PluginHandle, TauriPlugin},
19};
20
21pub use models::*;
22
23mod error;
24mod models;
25
26pub use error::{Error, Result};
27
28#[cfg(target_os = "android")]
29const PLUGIN_IDENTIFIER: &str = "app.tauri.nfc";
30
31#[cfg(target_os = "ios")]
32tauri::ios_plugin_binding!(init_plugin_nfc);
33
34/// Access to the nfc APIs.
35pub struct Nfc<R: Runtime>(PluginHandle<R>);
36
37#[derive(Deserialize)]
38struct IsAvailableResponse {
39    available: bool,
40}
41
42#[derive(Serialize)]
43struct WriteRequest {
44    records: Vec<NfcRecord>,
45}
46
47impl<R: Runtime> Nfc<R> {
48    /// Checks whether NFC is supported by the device and currently usable by the app.
49    ///
50    /// On Android this is `false` when the device has no NFC adapter or when NFC is
51    /// disabled in the device settings.
52    /// On iOS this is `false` when the `NFCReaderUsageDescription` entry is missing from the
53    /// `Info.plist` file or when NFC tag reading is not available on the device.
54    pub fn is_available(&self) -> crate::Result<bool> {
55        self.0
56            .run_mobile_plugin::<IsAvailableResponse>("isAvailable", ())
57            .map(|r| r.available)
58            .map_err(Into::into)
59    }
60
61    /// Scans an NFC tag, blocking until a tag matching the given [`ScanRequest::kind`] filters
62    /// is read or the scan fails.
63    ///
64    /// Set [`ScanRequest::keep_session_alive`] to `true` to keep the connection to the tag open
65    /// after it has been scanned, so that a following [`Self::write`] call writes to that tag.
66    ///
67    /// # Errors
68    ///
69    /// Returns an error when NFC is not available (see [`Self::is_available`])
70    /// or when the tag could not be read.
71    pub fn scan(&self, payload: ScanRequest) -> crate::Result<ScanResponse> {
72        self.0
73            .run_mobile_plugin("scan", payload)
74            .map(|v| ScanResponse { tag: v })
75            .map_err(Into::into)
76    }
77
78    /// Writes the given NDEF records to an NFC tag, blocking until the write completes or fails.
79    ///
80    /// Because this API does not take a scan kind, on Android it can only write to the tag of an
81    /// ongoing session, so it must be preceded by a [`Self::scan`] call with
82    /// [`ScanRequest::keep_session_alive`] set to `true`.
83    /// On iOS an NDEF reader session is started when there is no ongoing session, and the
84    /// records are written to the first tag that is scanned.
85    ///
86    /// # Errors
87    ///
88    /// Returns an error when NFC is not available (see [`Self::is_available`]), when there is no
89    /// connected tag on Android, when the tag is read-only, when it cannot hold the message or
90    /// when it does not support the NDEF format.
91    pub fn write(&self, records: Vec<NfcRecord>) -> crate::Result<()> {
92        self.0
93            .run_mobile_plugin("write", WriteRequest { records })
94            .map_err(Into::into)
95    }
96}
97
98/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the NFC APIs.
99pub trait NfcExt<R: Runtime> {
100    /// Returns the [`Nfc`] instance managed by the plugin.
101    fn nfc(&self) -> &Nfc<R>;
102}
103
104impl<R: Runtime, T: Manager<R>> crate::NfcExt<R> for T {
105    fn nfc(&self) -> &Nfc<R> {
106        self.state::<Nfc<R>>().inner()
107    }
108}
109
110/// Initializes the plugin.
111pub fn init<R: Runtime>() -> TauriPlugin<R> {
112    Builder::new("nfc")
113        .setup(|app, api| {
114            #[cfg(target_os = "android")]
115            let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "NfcPlugin")?;
116            #[cfg(target_os = "ios")]
117            let handle = api.register_ios_plugin(init_plugin_nfc)?;
118            app.manage(Nfc(handle));
119            Ok(())
120        })
121        .build()
122}