99 lines
2.5 KiB
JavaScript
99 lines
2.5 KiB
JavaScript
import {useEffect, useState} from 'react';
|
|
import {Text, View} from 'react-native';
|
|
import NfcManager, {Ndef, NfcEvents} from 'react-native-nfc-manager';
|
|
import {Button, Snackbar} from 'react-native-paper';
|
|
|
|
export default function Nfc() {
|
|
const [hasNfc, setHasNFC] = useState(null);
|
|
const [foundNfcTag, setFoundNfcTag] = useState('');
|
|
const [nfcScanningActive, setNfcScanningActive] = useState(false);
|
|
const [snackbarVisible, setSnackbarVisible] = useState(false);
|
|
const [snackbarMessage, setSnackbarMessage] = useState('');
|
|
|
|
useEffect(() => {
|
|
const checkIsSupported = async () => {
|
|
const deviceIsSupported = await NfcManager.isSupported();
|
|
|
|
setHasNFC(deviceIsSupported);
|
|
if (deviceIsSupported) {
|
|
await NfcManager.start();
|
|
}
|
|
};
|
|
|
|
checkIsSupported();
|
|
|
|
NfcManager.setEventListener(NfcEvents.DiscoverTag, tag => {
|
|
console.log(
|
|
'tag found',
|
|
tag,
|
|
Ndef.uri.decodePayload(tag.ndefMessage[0].payload),
|
|
);
|
|
|
|
setFoundNfcTag(Ndef.uri.decodePayload(tag.ndefMessage[0].payload));
|
|
|
|
setSnackbarVisible(true);
|
|
|
|
// fetch
|
|
|
|
setTimeout(() => {
|
|
setSnackbarVisible(false);
|
|
}, 2000);
|
|
});
|
|
|
|
return () => {
|
|
NfcManager.setEventListener(NfcEvents.DiscoverTag, null);
|
|
};
|
|
}, []);
|
|
|
|
const readTag = async () => {
|
|
await NfcManager.registerTagEvent();
|
|
setNfcScanningActive(true);
|
|
};
|
|
|
|
const unregisterReadTag = async () => {
|
|
await NfcManager.unregisterTagEvent();
|
|
setNfcScanningActive(false);
|
|
};
|
|
|
|
if (!hasNfc) {
|
|
return (
|
|
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
|
|
<Text>NFC not supported</Text>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<View
|
|
style={{
|
|
flex: 1,
|
|
justifyContent: 'center',
|
|
alignItems: 'center',
|
|
}}>
|
|
{nfcScanningActive ? (
|
|
<>
|
|
<Button mode="contained" onPress={unregisterReadTag}>
|
|
Deactivate NFC Tag scanning
|
|
</Button>
|
|
|
|
<Text style={{marginTop: 10}}>Found tag:</Text>
|
|
<Text>{foundNfcTag}</Text>
|
|
</>
|
|
) : (
|
|
<Button mode="contained" onPress={readTag}>
|
|
Activate NFC Tag scanning
|
|
</Button>
|
|
)}
|
|
<Snackbar
|
|
visible={snackbarVisible}
|
|
onDismiss={() => setSnackbarVisible(false)}
|
|
action={{
|
|
label: 'OK',
|
|
onPress: () => setSnackbarVisible(false),
|
|
}}>
|
|
{snackbarMessage}
|
|
</Snackbar>
|
|
</View>
|
|
);
|
|
}
|