I am making a react native app in which I want to make payments through POS via NFC. But I am facing error in getting data through NFC. I have used react-native-nfc-manager, it is making sure that my device has NFC support but not giving me the data when I bring my device near the POS.
I tried this code ,
import React, { useState, useEffect } from "react";
import { View, Text, Button, Alert } from "react-native";
import NfcManager, { NfcEvents, NdefParser } from "react-native-nfc-manager";
const App = () => {
const [nfcData, setNfcData] = useState(null);
useEffect(() => {
// Function to check NFC support
const checkNfcSupport = async () => {
try {
// Check if NFC is supported
const isSupported = await NfcManager.isSupported();
if (isSupported) {
console.log("NFC is supported on this device");
// Initialize NFC manager
await NfcManager.start();
// Add NFC tag detection event listener
NfcManager.setEventListener(NfcEvents.DiscoverTag, async (tag) => {
console.log("Scanned NFC Tag:", tag);
Alert.alert("Scanned NFC Tag:", tag);
if (tag.ndefMessage && tag.ndefMessage.length > 0) {
const parsedNdefMessage = NdefParser.parseTextPayload(
tag.ndefMessage[0].payload
);
console.log("NFC Tag Data:", parsedNdefMessage);
setNfcData(parsedNdefMessage);
}
// Close the NFC session
NfcManager.setAlertMessageIOS("NFC tag scanned");
await NfcManager.unregisterTagEvent();
});
} else {
console.log("NFC is not supported on this device");
}
} catch (error) {
console.error("Error checking NFC support:", error);
}
};
// Call the function to check NFC support
checkNfcSupport();
// Clean up NFC manager on unmount
return () => {
NfcManager.setEventListener(NfcEvents.DiscoverTag, null);
NfcManager.unregisterTagEvent().catch(() => {});
NfcManager.cancelTechnologyRequest().catch(() => {});
NfcManager.disable().catch(() => {});
};
}, []);
// Function to handle Scan NFC Tag button press
const handleScanNfcTag = async () => {
try {
// Check if NFC is supported
const isSupported = await NfcManager.isSupported();
if (isSupported) {
// Enable NFC scanning
await NfcManager.registerTagEvent();
setNfcData(null);
} else {
console.log("NFC is not supported on this device");
}
} catch (error) {
console.error("Error checking NFC support:", error);
}
};
return (
<View>
<Text>Checking NFC Support</Text>
<Button title="Scan NFC Tag" onPress={handleScanNfcTag} />
{nfcData && (
<View>
<Text>NFC Tag Data:</Text>
<Text>{JSON.stringify(nfcData)}</Text>
</View>
)}
</View>
);
};
export default App;