skip to Main Content

I got this code which works fine when the app is open. I want to be able to transfer the data even if the app is closed, or at least show an alert to open the app when you get the NFC tag near to the mobile. I am using react-native-nfc-manager.

My goal is to make it work in Android and iOS, but it will be fine if it only works in Android for the moment.



import React, { useEffect, useState } from 'react';
import {
  Text,
  SafeAreaView,
  View,
  TouchableOpacity,
  StyleSheet
} from 'react-native';

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

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

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

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

    checkIsSupported()
  }, [])

  useEffect(() => {
    readTag()
    NfcManager.setEventListener(NfcEvents.DiscoverTag, (tag) => {
      console.log('tag found', tag)
      console.log(tag.ndefMessage[0].payload.toString('utf8'))

      if (tag.ndefMessage && tag.ndefMessage.length > 0) {
        // Iterate through the NDEF records
        for (let i = 0; i < tag.ndefMessage.length; i++) {
          const record = tag.ndefMessage[i];
          console.log(record)

          // Check the record's type (TNF) and payload
          if (record.tnf === 1) { // TNF 1 corresponds to well-known types (e.g., text or URI)
            // Assuming the payload is text data, you can decode it
            const payloadText = String.fromCharCode.apply(null, record.payload);
            console.log(`NDEF Record ${i + 1}: ${payloadText}`);
          }
        }
      }
    })

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

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

  if (hasNfc === null) return null;

  if (!hasNfc) {
    return (
      <View style={styles.sectionContainer}>
        <Text>NFC not supported</Text>
      </View>
    )
  }

  return (
    <SafeAreaView style={styles.sectionContainer}>

    </SafeAreaView>
  );


}

const styles = StyleSheet.create({
  sectionContainer: {
    backgroundColor: 'white',
    flex: 1,
    alignItems: 'center'
  },
})



export default App;


2

Answers


  1. You cannot read from NFC when your app is closed (because obviously your app is not running), there are 2 different ways to configure a specific NFC Tag to start your app in the foreground (one for iOS and one for Android).

    Then once your App has been started by a correctly configured NFC Tag you can then read it.

    Login or Signup to reply.
  2. In Android add to AndroidManifest.xml new intent-filter

    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="application/your-stream" />
    </intent-filter> 
    

    It will launch your app.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search