Tuesday, August 23, 2022
HomeWeb DevelopmentHow one can use NFC tags in React Native

How one can use NFC tags in React Native


Close to subject communication, or NFC, permits for knowledge to be transferred between units in shut proximity to one another. NFC tags are stickers or wristbands embedded with tiny microchips that retailer info and will be learn by NFC readers inside ten centimeters.

With NFC tags, you may simply switch small quantities of knowledge, like app URLs, encrypted financial institution accounts, and extra. The most important benefit of NFC is that it doesn’t require pairing or any handbook enter to determine a connection. You possibly can switch knowledge with only a faucet, which we’ll show later. On this article, we’ll cowl what NFC tags are and the way we are able to use them with React Native. Let’s get began!

We will use NFC tags in purposes the place we have to trade digitized knowledge shortly. NFC tags comprise storage reminiscence and a radio chip. Resulting from magnetic induction, NFC tags don’t have an influence supply of their very own. As a substitute, they obtain energy from the system that reads them.

Primarily, when an NFC reader is introduced inside ten centimeters of an NFC tag, the NFC tag turns into energized, transmitting any knowledge saved inside its microchip. The data trade is accomplished when the reader validates the knowledge. NFC readers can solely join to at least one NFC tag at a time, minimizing unintentional transactions.

How do NFC tag readers work?

Beforehand, we talked about that NFC tag readers function the facility supply, studying info from passive NFC tags. NFC tag readers require an influence supply to cross an electrical present via their coil to the NFC tags, producing a magnetic subject across the reader because of this.

Resulting from Faraday’s legislation of induction, bringing a tag inside this magnetic subject’s vary ends in inductive coupling between the 2 coils, which is when the knowledge trade happens.

Now that we perceive the fundamentals of NFC tags and NFC tag readers, let’s learn to write the React Native code that reads and writes an NFC tag. First, let’s initialize a brand new React Native undertaking utilizing the command beneath:

npx react-native init NFCTutorial

The command above will set up a brand new React Native boilerplate on the location of your selection, so you may get began writing your code shortly. Run the command beneath to put in the iOS dependencies utilizing pods. CocoaPods is a dependency supervisor for iOS programming languages like Swift:

cd ios && pod set up && cd ..

Then, run npm begin to begin Metro bundler and npm ios to run the undertaking on an iOS simulator.

On this tutorial, we’ll use react-native-nfc-manager. However, earlier than leaping into the code, we have to configure each Android and iOS platforms to allow NFC. Though we’ll undergo the configuration for each Android and iOS platforms, we’ll demo studying and writing NFC tags solely on an iOS system.

NFC configuration for Android

To entry an Android system’s NFC {hardware} and correctly deal with NFC intents, we’ll declare this stuff within the AndroidManifest.xml file:

The uses-feature component ensures that the applying solely exhibits up in Google Play for units which have NFC {hardware}:

<uses-feature android:title="android.{hardware}.nfc" android:required="true" />

The NFC uses-permission component permits entry to the NFC {hardware}:

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

Requesting NFC entry on iPhone

To start out, you’ll must be registered with the Apple Developer program; you’ll additionally must create an app identification for the applying as a way to check the NFC undertaking on an iOS system.

  • From inside Xcode on a Mac, navigate to Xcode → Preferences → Accounts
  • Click on on the + icon on the decrease lefthand aspect so as to add your Apple ID
  • Choose your account. It should present inside the primary account window on the precise underneath Staff as (Private Staff) and Function as Consumer

Xcode Account Registration UI

  • From the menu bar, Click on on Window → Units and Simulators → Units
  • Join your iPhone with a lightning cable and choose it because the construct vacation spot via the energetic scheme dropdown to the precise
  • Subsequent, open the undertaking we put in earlier on Xcode
  • Below the Basic tab, change the bundle identifier to a novel identifier

Within the Signing and capabilities tab, choose the suitable workforce you’re utilizing for the undertaking. Then, beneath the Signing and capabilities tab, choose Capabilities or click on the + signal and seek for Close to subject communication tag to allow NFC functionality on the undertaking:

Enable NFC Capabilities Xcode


Extra nice articles from LogRocket:


Discover how Xcode has created a folder referred to as entitlements containing the app capabilities:

Xcode Entitlements Folder

Lastly, let’s edit the data.plist file so as to add the next strains of code that describe the undertaking:

<key>NFCReaderUsageDescription</key>
<string>Studying NFC with react native</string>

And that’s all of the configuration wanted! Go forward and hit the run button on Xcode so we are able to view the undertaking on the linked iPhone system. Now, let’s go forward and write our code!

How one can learn an NFC tag with React Native

First, let’s set up the react-native-nfc-manager library:

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

Bear in mind to run cd ios && pod set up once more.

Verify if the present system has NFC assist

We have to import the react-native-nfc-manager library, then we’ll use the isSupported() technique to find out if a tool has NFC assist. Within the code beneath, we create a state that might be up to date after we discover out if the system helps NFC:

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

 const [hasNfc, setHasNFC ] = useState(null);

We’ll replace the state in a useEffect Hook when the element mounts. As soon as we verify that NFC is supported on the system, we’ll go forward and initialize the NFC module with the begin() technique:

useEffect(() => {
    const checkIsSupported = async () => {
      const deviceIsSupported = await NfcManager.isSupported()

      setHasNFC(deviceIsSupported)
      if (deviceIsSupported) {
        await NfcManager.begin()
      }
    }

    checkIsSupported()
  }, [])

Now, let’s write the code that can learn an NFC tag:

useEffect(() => {
    NfcManager.setEventListener(NfcEvents.DiscoverTag, (tag) => {
      console.log('tag discovered')
    })

    return () => {
      NfcManager.setEventListener(NfcEvents.DiscoverTag, null);
    }
  }, [])


  const readTag = async () => {
    await NfcManager.registerTagEvent();
  }

Within the useEffect() Hook above, the occasion listener is listening for an occasion referred to as onDiscoverTag. You too can use setAlertMessages() to set a type of UI message for the customers to see. We use registerTagEvent() to start the method of detecting NFC tags and unregisterTagEvent() to cancel it.

If the system has NFC assist, we’ll conditionally render a button, and if not, we’ll render a message. The code beneath is for the button that can name the readTag() when clicked:

if (hasNfc === null) return null;

  if (!hasNfc) {
    return (
      <View fashion={types.sectionContainer}>
        <Textual content>NFC not supported</Textual content>
      </View>
    )
  }

  return (
    <SafeAreaView fashion={types.sectionContainer}>
      <Textual content>Good day world</Textual content>
      <TouchableOpacity fashion={[styles.btn, styles.btnScan]} onPress={readTag}>
        <Textual content fashion={{ colour: "white" }}>Scan Tag</Textual content>
      </TouchableOpacity>
      <TouchableOpacity fashion={[styles.btn, styles.btnCancel]} onPress={cancelReadTag}>
        <Textual content fashion={{ colour: "white" }}>Cancel Scan</Textual content>
      </TouchableOpacity>
    </SafeAreaView>
  );

The picture beneath exhibits the undertaking on a simulator that doesn’t assist NFC scanning:

Project Simulator NFC Disabled

The screenshot beneath exhibits what the undertaking will appear to be on a bodily system:

Hello World Project Device

While you faucet the scan tag button, like within the picture beneath, the system might be able to learn an NFC tag:

Scan Tag Read Scan NFC Tag

 

How one can write an NFC tag

Thus far, we’ve established how you can verify if a tool helps NFC tags, and we’ve realized how you can learn an NFC tag to entry the knowledge saved in it. Now, we’ll learn to encode info into an NFC tag in order that when a reader reads it, they may entry the knowledge we wrote to the tag. For example, we’ll encode the LogRocket URL:

const writeNFC = async() => {
    let end result = false;

    attempt {
      await NfcManager.requestTechnology(NfcTech.Ndef);

      const bytes = Ndef.encodeMessage([Ndef.uriRecord('https://blog.logrocket.com/')]);

      if (bytes) {
        await NfcManager.ndefHandler
          .writeNdefMessage(bytes);
        end result = true;
      }
    } catch (ex) {
      console.warn(ex);
    } lastly {
      NfcManager.cancelTechnologyRequest();
    }

    return end result;
  }

Within the code above, we requested a specific NFC know-how via NfcManager.requestTechnology. In our case, it’s the Ndef know-how, a knowledge format. Then, we encode the URL we need to write utilizing Ndef.encodeMessage and write it utilizing the writeNdefMessage(bytes).

Now, we’ll create a button that can name this operate when a person needs to write down the LogRocket weblog URL to an NFC tag:

<TouchableOpacity fashion={[styles.btn, styles.btnWrite]} onPress={writeNFC}>
        <Textual content fashion={{ colour: "white" }}>Write Tag</Textual content>
 </TouchableOpacity>

Due to this fact, when the button is clicked, the NFC drawer is able to encode the LogRocket URL to an NFC tag:

NFC Drawer Encode URL

Conclusion

NFC know-how is utilized in many facets of our on a regular basis lives, together with contactless cost, ticket redemption at live shows, and venue location check-in, simply to call just a few.

On this article, we explored how you can learn and write an NFC tag to both encode or entry info inside it. We constructed a pattern software utilizing React Native and iOS to simply switch a URL, however, you may construct on the knowledge on this tutorial to implement NFC tags in your personal undertaking. I hope you loved studying, and remember to depart a remark if in case you have any questions. Pleased coding! 

LogRocket: Immediately recreate points in your React Native apps.

LogRocket is a React Native monitoring answer that helps you reproduce points immediately, prioritize bugs, and perceive efficiency in your React Native apps.

LogRocket additionally helps you improve conversion charges and product utilization by exhibiting you precisely how customers are interacting along with your app. LogRocket’s product analytics options floor the explanation why customers do not full a specific stream or do not undertake a brand new function.

Begin proactively monitoring your React Native apps — .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments