react-native-nfc-manager

repository·main·Indexed 23 days ago

https://github.com/revtel/react-native-nfc-manager

A React Native library for accessing NFC (Near Field Communication) features on Android and iOS. It allows developers to read and write NFC tags, supporting various technologies including Ndef, NfcA, IsoDep, and platform-specific handlers like MifareClassic (Android) and FelicaIOS (iOS). The library includes a comprehensive NDEF utility for encoding and decoding messages, as well as tools for managing NFC session lifecycles and handling native exceptions.

Tokens
4.9K
Snippets
10
Records
25
Agent score
82%

What's inside react-native-nfc-manager

  1. How NFC technology requests work

    main

    Using the library follows a 4-step lifecycle:

    1. Initialize: Call NfcManager.start() to prepare the manager.
    2. Request Technology: Use NfcManager.requestTechnology(NfcTech.<TYPE>) to tell the system which specific NFC technology you want to listen for (e.g., NfcTech.Ndef).
    3. Access Handler: Once the technology is requested, access the corresponding handler via the NfcManager object (e.g., NfcManager.ndefHandler). Use this handler to call specific methods like getNdefMessage().
    4. Cleanup: Always call NfcManager.cancelTechnologyRequest() in a finally block to stop scanning and release resources.
  2. Configure Android for NFC

    main

    To use NFC on Android, add the following permission to your AndroidManifest.xml:

    <uses-permission android:name="android.permission.NFC" />

    Android 12 Support

    To support Android 12, you must use v3.11.1 or higher and update your compileSdkVersion to 31 in your build.gradle file to handle PendingIntent mutability requirements:

    buildscript {
        ext {
            ...
            compileSdkVersion = 31
            ...
        }
        ...
    }
     <uses-permission android:name="android.permission.NFC" />
  3. Configure iOS for NFC

    main

    To use NFC on iOS, follow these steps in Xcode and your project configuration:

    1. Enable Capability: In the Apple Developer site, enable the NFC capability for your app.
    2. Update Info.plist: Add the NFCReaderUsageDescription key to explain why your app uses NFC.
      <key>NFCReaderUsageDescription</key>
      <string>We need to use NFC</string>
    3. Add ISO7816 Identifiers (if applicable): If writing ISO7816 tags, add application identifiers (aid) to your info.plist:
      <key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
      <array>
        <string>D2760000850100</string>
        <string>D2760000850101</string>
      </array>
    4. FeliCa Support: If using NfcTech.FelicaIOS, you must add the following system codes to Info.plist to prevent crashes:
      <key>com.apple.developer.nfc.readersession.felica.systemcodes</key>
      <array>
        <string>8005</string>
        <string>8008</string>
        <string>0003</string>
        <string>fe00</string>
        <string>90b7</string>
        <string>927a</string>
        <string>12FC</string>
        <string>86a7</string>
      </array>
    5. Signing & Capabilities: In Xcode, add the Near Field Communication Tag Reading capability. This will generate a .entitlement file. Ensure the entitlement is correctly configured.
    <key>NFCReaderUsageDescription</key>
    <string>We need to use NFC</string>
  4. Install react-native-nfc-manager

    main

    Install the package using npm:

    npm i --save react-native-nfc-manager

    iOS Setup

    Since this library uses native modules, you must install the pods:

    cd ios && pod install && cd ..

    Android Setup

    The library supports auto-linking, so no additional installation steps are required for Android.

  5. Read NDEF tags (Quickstart)

    main

    The most common use case is reading NDEF tags. The workflow involves:

    1. Calling NfcManager.start() once.
    2. Requesting the specific technology via NfcManager.requestTechnology(NfcTech.Ndef).
    3. Retrieving the tag data with NfcManager.getTag().
    4. Cleaning up with NfcManager.cancelTechnologyRequest().
    import React from 'react';
    import {View, Text, TouchableOpacity, StyleSheet} from 'react-native';
    import NfcManager, {NfcTech} from 'react-native-nfc-manager';
    
    // Pre-step, call this before any NFC operations
    NfcManager.start();
    
    function App() {
      async function readNdef() {
        try {
          // register for the NFC tag with NDEF in it
          await NfcManager.requestTechnology(NfcTech.Ndef);
          // the resolved tag object will contain `ndefMessage` property
          const tag = await NfcManager.getTag();
          console.warn('Tag found', tag);
        } catch (ex) {
          console.warn('Oops!', ex);
        } finally {
          // stop the nfc scanning
          NfcManager.cancelTechnologyRequest();
        }
      }
    
      return (
        <View style={styles.wrapper}>
          <TouchableOpacity onPress={readNdef}>
            <Text>Scan a Tag</Text>
          </TouchableOpacity>
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      wrapper: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      },
    });
    
    export default App;
  6. Configure registerTagEvent options

    main

    When calling registerTagEvent, you can provide an options object to configure the tag discovery behavior. The following default options are used if not provided:

    • alertMessage: String. The message shown to the user (e.g., 'Please tap NFC tags').
    • invalidateAfterFirstRead: Boolean. If true, the event listener is invalidated after the first tag is discovered.
    • isReaderModeEnabled: Boolean. Enables reader mode (primarily for iOS).
    • readerModeFlags: Number. Flags for reader mode.
    • readerModeDelay: Number. Delay in milliseconds.
    const DEFAULT_REGISTER_TAG_EVENT_OPTIONS = {
      alertMessage: 'Please tap NFC tags',
      invalidateAfterFirstRead: false,
      isReaderModeEnabled: false,
      readerModeFlags: 0,
      readerModeDelay: 250,
    };
  7. NFC Technology Handlers Reference

    main

    The following table maps NFC technologies to their respective handlers available in the NfcManager object. If you need to use a specific technology, refer to the corresponding handler to find available methods.

    NFC TechnologiesHandlers
    NdefNdefHandler
    NfcANfcAHandler
    IsoDepIsoDepHandler
    NfcB-
    NfcF-
    NfcVNfcVHandler
    MifareClassicMifareClassicHandlerAndroid
    MifareUltralightMifareUltralightHandlerAndroid
    MifareIOS-
    Iso15693IOSIso15693HandlerIOS
    FelicaIOS-
  8. NFC Technology Compatibility Matrix

    main

    Use this table to verify if a specific NFC technology is supported on Android or iOS.

    NFC TechnologiesAndroidiOS
    Ndef
    NfcA
    IsoDep
    NfcB
    NfcF
    NfcV
    MifareClassic
    MifareUltralight
    MifareIOS
    Iso15693IOS
    FelicaIOS
  9. Manage NFC lifecycle with NfcManagerBase

    main

    The NfcManagerBase class provides the core methods for managing the NFC session and interacting with tags.

    Core Methods:

    • start(): Starts the NFC session.
    • isSupported(tech): Checks if a specific technology (from NfcTech) is supported on the device.
    • registerTagEvent(options): Registers an event listener for tag discovery.
    • unregisterTagEvent(): Stops listening for tag discovery events.
    • getTag(): Retrieves the currently discovered tag.
    • setEventListener(name, callback): Sets a callback for specific NfcEvents.
    • writeNdefMessage(bytes, options): Writes NDEF data to a tag.
    • getNdefMessage(): Retrieves the NDEF message from a tag.

    Technology Handlers: Access specialized handlers via getters:

    • ndefHandler: For NDEF operations.
    • nfcAHandler: For NFC-A technology.
    • nfcVHandler: For NFC-V technology.
    • isoDepHandler: For ISO-DEP technology.
  10. Create NDEF records using the NDEF object

    main
    The NDEF object provides several helper methods to create different types of NDEF records. Records are categorized into PrimitiveRecord, WellKnownRecord, and ExtraTypeRecord types. You can use these helpers to generate records for text, URIs, WiFi credentials, or custom MIME types.