Modified handleImagePicker with correct error handling. Able to scan QR code from images and give alert for non QR images

This commit is contained in:
2024-06-17 21:07:59 +08:00
parent 42c938b105
commit ad197abe6e

View File

@@ -149,19 +149,29 @@ const QRScannerScreen: React.FC<QRScannerScreenProps> = ({ clearScanData }) => {
handleQRCodeScanned({ type: 'TEST', data: 'TEST123' }); handleQRCodeScanned({ type: 'TEST', data: 'TEST123' });
}; };
//https://medium.com/@funti009/create-a-mobile-qr-scanner-that-scans-via-camera-and-image-in-the-gallery-react-native-expo-ee7098a265d7
// Refactored to use Camera.scanFromURLAsync instead
// Function to handle QR code scanning from the image picker // Function to handle QR code scanning from the image picker
const handleImagePicker = async () => { const handleImagePicker = async () => {
clearScanDataInternal();
const result = await ImagePicker.launchImageLibraryAsync({ const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images, mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: false, // Disabling the crop functionality allowsEditing: false, // Disabling the crop functionality
quality: 1, quality: 1,
}); });
if (result && result.assets[0].uri) {
//if (result && result.assets[0].uri) { // KIV this....
if (result && result.assets && result.assets.length > 0 && result.assets[0].uri) { // this is to unsure the uri is not empty
try { try {
const scannedResults = await scanFromURLAsync(result.assets[0].uri); const scannedResult = await scanFromURLAsync(result.assets[0].uri);
if (scannedResults.length > 0) { if (!scannedResult.data) { // This will check if no QR was scanned
const dataNeeded = scannedResults[0].data; // Not sure why by passing the scannedResults.data is not working , only works when I use scannedResults[0].data..... KIV >.<
const dataNeeded = scannedResult[0].data;
handleQRCodeScanned({ type: 'QR_CODE', data: dataNeeded }); handleQRCodeScanned({ type: 'QR_CODE', data: dataNeeded });
} else { } else {
setScannedData("No QR Code Found"); setScannedData("No QR Code Found");
@@ -172,7 +182,9 @@ const QRScannerScreen: React.FC<QRScannerScreenProps> = ({ clearScanData }) => {
Alert.alert('Failed to scan QR code from image.'); Alert.alert('Failed to scan QR code from image.');
} }
} }
}; };
// For Splash, for some reason need to be near the end of the function... // For Splash, for some reason need to be near the end of the function...
// or else permission for camera is not asked // or else permission for camera is not asked