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
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.
In Android add to AndroidManifest.xml new intent-filter
It will launch your app.