This video is available to students only

In this lesson, we will focus on how to deal with NDEF, covering:

  • Reading and parsing the NDEF from NFC tags

  • Building and writing NDEF into NFC tags

Detect NFC features#

Before handling NDEF, let's first add some codes to check the NFC feature availability.

First, open App.js from the previous TagCounterGame app.

Paste the import NfcManager line back to our HomeScreen.

Then, migrate the useEffect hook, so now we have the hasNfc state to check if the NFC feature is available and the enabled state to check if the NFC is enabled.

After that, we create a renderNfcButtons function and paste the original UI code into it.

Then we go back to TagCounterGame's App.js and copy the conditional rendering codes into our renderNfcButtons function.

Oh, it looks like we forgot to import TouchableOpacity.

Save and refresh, and we can see our simulator says, "your device doesn't support NFC," which is expected.

Read NFC Tags#

The next step is, of course, to scan our NFC tags.

Remember in our previous TagCounterGame app, we used registerTagEvent and setEventListener to scan our tags.

Here, we will use a different approach. Let's call NfcManager.requestTechnology. As you can see from the type hint, the first parameter is called tech, which is the technology type we'd like to request, and Ndef itself is also an NFC technology type.

In order to use the correct tech type, we should import NfcTech from our library.

Once this API is resolved, it means the NFC tag with our expected technology has been discovered.

So at this point, we can call NfcManager.getTag to retrieve the NFC tag object. If the NFC tag contains valid NDEF data, there will be a ndefMessage property inside the tag object, as we saw before.

After scanning, we will have to call NfcManager.cancelTechnologyRequest to clean up.

Then what we'd like to do is to pass the tag object as parameters into the TagDetailScreen, and we can accomplish this by using the second parameter of the navigation.navigate function.

We also wrap our code in a try-catch block to prevent unexpected errors. In this case, no critical exceptions will be thrown, so we can simply ignore them. We also move the cancelTechnology API into the finally block because it's the cleanup operation and should always be called.

Then, call the readNdef function from our TAP button.

Let's quickly see our readNdef function again: this requestTechnology pattern will be our primary method for NFC tag scanning for the rest of the course. Remember, this API is an async function and only resolves when the tag is discovered.

Before testing, we still need to update our TagDetailScreen so that it can display the tag object we pass. First, destructure the route from props, and the data we're looking for will be in the route.params.

For now, we simply wrap the stringified tag object inside a Text element.

Start a new discussion. All notification go to the author.