Reac-Native NFC tag read

512 Views Asked by At

I'm making a very simple test application, but i'm having some problems. I'm trying to make a react-native app that reads NFC cards. Simple enought. But, everytime I try to execute the app on my phone it does not read any NFC tags. The phone model is a Xiaomi red mi 11. I'm using react-native with expo ejected (because I needed to add the permissions on the AndroidManifest.xml file) and react-native-nfc-manager latest version. Is there anything I am missiong out?

Code:

import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import NfcManager, { NfcTech } from 'react-native-nfc-manager';

const App = () => {
  const [nfcData, setNfcData] = useState(null);
  useEffect(() => {
    NfcManager.start();
    return () => {
      NfcManager.stop();
    };
  }, []);
  const startNfcListener = async () => {
    try {
      await NfcManager.requestTechnology(NfcTech.Ndef);
      NfcManager.setEventListener(NfcTech.Ndef, (tag) => {
        console.log('NFC Tag:', tag);
        setNfcData(tag);
        NfcManager.setAlertMessageIOS('NFC Tag Detected');
        NfcManager.unregisterTagEvent().catch(() => 0);
      });
      NfcManager.setAlertMessageIOS('Aproxime o NFC Tag do dispositivo.');
    } catch (ex) {
      console.warn(ex);
    }
  };
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>NFC Data: {nfcData}</Text>
      <TouchableOpacity onPress={startNfcListener} style={{ marginTop: 20 }}>
        <Text>Start NFC Reader</Text>
      </TouchableOpacity>
    </View>
  );
};

export default App;

The app shoud read the NFC tag/card

1

There are 1 best solutions below

1
Deepanshu yadav On

Add uses-permission into your AndroidManifest.xml

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

If event listener not work correctly call this function before NfcManager.setEventListener

NfcManager.registerTagEvent();