Coder Social home page Coder Social logo

hkar19 / react-native-nfc-manager Goto Github PK

View Code? Open in Web Editor NEW

This project forked from revtel/react-native-nfc-manager

0.0 0.0 0.0 4.06 MB

React Native NFC module for Android & iOS

License: Apache License 2.0

JavaScript 34.51% Java 39.36% Objective-C 25.85% Ruby 0.28%

react-native-nfc-manager's Introduction

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!

We also have a slack channel, you're welcome to chat with us for any issue or idea! join us here

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

Also See

[Demo App] NfcOpenReWriter

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

react-native-nfc-rewriter

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

[Bonus] Reconnect.js

Super useful library to help you share states between sibling and nested React components.

Check it out!

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

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"]
        }
      ]
    ]
  }
}

react-native-nfc-manager's People

Contributors

acasademont avatar ajacquierbret avatar alexandraolegovna avatar april-ayres avatar changtimwu avatar christianchown avatar christophebelpaire avatar clickclickonsal avatar clrsustainas avatar dulmandakh avatar evanbacon avatar frans-l avatar guck111 avatar hannesoberreiter avatar hataguchi avatar hblab-nghianh avatar jimteva avatar jlkalberer avatar matzielab avatar meanurag avatar mharj avatar monder avatar nicholasbertazzon avatar pedroyan avatar poison avatar rrrasti avatar spedy avatar symous avatar whitedogg13 avatar zamfi99 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.