npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-native-nfc-manager-dibeling

v1.0.6

Published

A NFC module for react native.

Downloads

9

Readme

react-native-nfc-manager

npm version build issues

Bring NFC feature to React Native. Inspired by phonegap-nfc and react-native-ble-manager

Contributions are welcome!

Made with ❤️ by whitedogg13 and revteltech

Install

javascript part

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

native part

This library use native-modules, so you will need to do pod install for iOS:

cd ios && pod install && cd ..

For Android, it should be properly auto-linked, so you don't need to do anything.

Setup

Please see here

Android 12

To support Android 12, you will need to update compileSdkVersion in your android/build.gradle like this:

buildscript {
    ext {
        ...
        compileSdkVersion = 31
        ...
    }
    ...
}

The reason for this is because Android puts new limitation on PendingIntent:

Starting with Build.VERSION_CODES.S, it will be required to explicitly specify the mutability of PendingIntents

The original issue is here

Also See

[Demo App] NfcOpenReWriter

We have a full featured NFC utility app available for download.

It also open sourced in this repo: React Native NFC ReWriter App

Basic Usage

If all you want to do is to read NDEF data, you can use this example:

import NfcManager, {NfcEvents} from 'react-native-nfc-manager';

// Pre-step, call this before any NFC operations
async function initNfc() {
  await NfcManager.start();
}

function readNdef() {
  const cleanUp = () => {
    NfcManager.setEventListener(NfcEvents.DiscoverTag, null);
    NfcManager.setEventListener(NfcEvents.SessionClosed, null);
  };

  return new Promise((resolve) => {
    let tagFound = null;

    NfcManager.setEventListener(NfcEvents.DiscoverTag, (tag) => {
      tagFound = tag;
      resolve(tagFound);
      NfcManager.setAlertMessageIOS('NDEF tag found');
      NfcManager.unregisterTagEvent().catch(() => 0);
    });

    NfcManager.setEventListener(NfcEvents.SessionClosed, () => {
      cleanUp();
      if (!tagFound) {
        resolve();
      }
    });

    NfcManager.registerTagEvent();
  });
}

Anything else, ex: write NDEF, send custom command, please read next section.

Advanced Usage

In high level, there're 3 steps to perform advanced NFC operations:

  1. request your specific NFC technology
  2. select the proper NFC technology handler, which is implemented as getter in main NfcManager object, including:
    • ndefHandler
    • nfcAHandler
    • isoDepHandler
    • iso15693HandlerIOS
    • mifareClassicHandlerAndroid
    • mifareUltralightHandlerAndroid
  3. call specific methods on the NFC technology handler
  4. clean up your tech registration

For example, here's an example to write NDEF:

import NfcManager, {NfcTech, Ndef} from 'react-native-nfc-manager';

// Pre-step, call this before any NFC operations
async function initNfc() {
  await NfcManager.start();
}

async function writeNdef({type, value}) {
  let result = false;

  try {
    // Step 1
    await NfcManager.requestTechnology(NfcTech.Ndef, {
      alertMessage: 'Ready to write some NDEF',
    });

    const bytes = Ndef.encodeMessage([Ndef.textRecord('Hello NFC')]);

    if (bytes) {
      await NfcManager.ndefHandler // Step2
        .writeNdefMessage(bytes); // Step3

      if (Platform.OS === 'ios') {
        await NfcManager.setAlertMessageIOS('Successfully write NDEF');
      }
    }

    result = true;
  } catch (ex) {
    console.warn(ex);
  }

  // Step 4
  NfcManager.cancelTechnologyRequest().catch(() => 0);
  return result;
}

Advanced: Mifare Ultralight usage

Here's an example to read a Mifare Ultralight tag:

import NfcManager, {NfcTech} from 'react-native-nfc-manager';

// Pre-step, call this before any NFC operations
async function initNfc() {
  await NfcManager.start();
}

async function readMifare() {
  try {
    // 0. Request Mifare technology
    let reqMifare = await NfcManager.requestTechnology(
      NfcTech.MifareUltralight,
    );
    if (reqMifare !== 'MifareUltralight') {
      throw new Error(
        '[NFC Read] [ERR] Mifare technology could not be requested',
      );
    }

    // 1. Get NFC Tag information
    const nfcTag = await NfcManager.getTag();
    console.log('[NFC Read] [INFO] Tag: ', nfcTag);

    // 2. Read pages
    const readLength = 60;
    let mifarePages = [];
    const mifarePagesRead = await Promise.all(
      [...Array(readLength).keys()].map(async (_, i) => {
        const pageOffset = i * 4; // 4 Pages are read at once, so offset should be in steps with length 4
        let pages = await NfcManager.mifareUltralightHandlerAndroid.mifareUltralightReadPages(
          pageOffset,
        );
        mifarePages.push(pages);
        console.log(`[NFC Read] [INFO] Mifare Page: ${pageOffset}`, pages);
        //await wait(500); // If Mifare Chip is to slow
      }),
    );

    // 3. Success
    console.log('[NFC Read] [INFO] Success reading Mifare');

    // 4. Cleanup
    _cleanup();
  } catch (ex) {
    console.warn('[NFC Read] [ERR] Failed Reading Mifare: ', ex);
    _cleanup();
  }
}

function _cleanup() {
  NfcManager.cancelTechnologyRequest().catch(() => 0);
}

To see more examples, please see React Native NFC ReWriter App

API

Please see here

FAQ

Please see here

Expo

This package cannot be used in the "Expo Go" app because it requires custom native code.

After installing this npm package, add the config plugin to the plugins array of your app.json or app.config.js:

{
  "expo": {
    "plugins": ["react-native-nfc-manager"]
  }
}

Next, rebuild your app as described in the "Adding custom native code" guide.

Props

The plugin provides props for extra customization. Every time you change the props or plugins, you'll need to rebuild (and prebuild) the native app. If no extra properties are added, defaults will be used.

  • nfcPermission (string | false): Sets the iOS NFCReaderUsageDescription permission message to the Info.plist. Setting false will skip adding the permission. Defaults to Allow $(PRODUCT_NAME) to interact with nearby NFC devices (Info.plist).
  • selectIdentifiers (string[]): Sets the iOS com.apple.developer.nfc.readersession.iso7816.select-identifiers to a list of supported application IDs (Info.plist).
  • systemCodes (string[]): Sets the iOS com.apple.developer.nfc.readersession.felica.systemcodes to a user provided list of FeliCa™ system codes that the app supports (Info.plist). Each system code must be a discrete value. The wild card value (0xFF) isn't allowed.

Example

{
  "expo": {
    "plugins": [
      [
        "react-native-nfc-manager",
        {
          "nfcPermission": "Custom permission message",
          "selectIdentifiers": ["A0000002471001"],
          "systemCodes": ["8008"]
        }
      ]
    ]
  }
}