Last active
January 31, 2024 13:37
-
-
Save eduardo-santos/99cfab9cbf951aca5b3038ad6c8d70c9 to your computer and use it in GitHub Desktop.
A helper class to easy manage the NFC tags reading using the awesome react-native-nfc-manager library.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import NfcManager, { Ndef } from "react-native-nfc-manager"; | |
let hasStartedNFC = false; | |
const decodeNdefRecord = record => { | |
if (Ndef.isType(record, Ndef.TNF_WELL_KNOWN, Ndef.RTD_TEXT)) { | |
return ["text", Ndef.text.decodePayload(record.payload)]; | |
} | |
if (Ndef.isType(record, Ndef.TNF_WELL_KNOWN, Ndef.RTD_URI)) { | |
return ["uri", Ndef.uri.decodePayload(record.payload)]; | |
} | |
return ["unknown", "---"]; | |
}; | |
const registerTagEvent = (callback = null) => { | |
NfcManager.registerTagEvent(tag => { | |
let parsed = null; | |
if (tag.ndefMessage && tag.ndefMessage.length > 0) { | |
const ndefRecords = tag.ndefMessage; | |
parsed = ndefRecords.map(decodeNdefRecord); | |
} | |
if (callback) { | |
callback({ tagValue: parsed[0][1] }); | |
} | |
}); | |
}; | |
const unregisterTagEvent = () => { | |
NfcManager.unregisterTagEvent(); | |
}; | |
const startNFCManager = async () => | |
NfcManager.start() | |
.then(result => ({ | |
Success: `Sucesso ${result}` | |
})) | |
.catch(error => ({ Error: error })); | |
const stopNFCManager = () => { | |
NfcManager.stop(); | |
}; | |
export const isNFCSupported = async () => NfcManager.isSupported(); | |
export const startNFC = async callback => { | |
const isSupported = await isNFCSupported(); | |
if (isSupported) { | |
const startResult = await startNFCManager(); | |
if (startResult.Success) { | |
registerTagEvent(callback); | |
hasStartedNFC = true; | |
return true; | |
} | |
return callback({ | |
Error: { | |
Title: "Ocorreu um erro ao iniciar o NFC Manager", | |
Message: startResult.Error | |
} | |
}); | |
} | |
return callback({ | |
Error: { | |
Title: "Dispositivo sem suporte para NFC", | |
Message: | |
"O seu dispositivo não possui suporte para leitura da tag NFC. Tente outro dispositivo." | |
} | |
}); | |
}; | |
export const stopNFC = () => { | |
if (hasStartedNFC) { | |
unregisterTagEvent(); | |
stopNFCManager(); | |
hasStartedNFC = false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
não teria um Helper exemplo para o TSX não ? tem muita coisa que não estou entendendo pq parece meio desatualizado, exemplo o Stop do stopNFCManager diz não existir função stop e tem vários outros campos dando erro