moaazsidat / react-native-qrcode-scanner

A QR code scanner component for React Native.
MIT License
2.03k stars 511 forks source link

Camera Preview does not show on either ios or android #357

Open cmd08010 opened 2 years ago

cmd08010 commented 2 years ago

Camera Preview is not working. QR Scanner is working, however so I know my camera permissions are set. i looked at: https://github.com/moaazsidat/react-native-qrcode-scanner/issues/73

And was not able to resolve it with any of the suggestions in this issue.

This occurred after updating to the newest qrcode scanner and newest camera - I have since downgraded in an attempt to fix it. - was on v1.5.4 and camera - v - 4.2.1

What's happening?

When using the QRSCANNER component - the camera view is not working - i am only seeing a blank screen.

How can it be reproduced?

import React, { useCallback, useContext, useRef, useState } from 'react';
import { View } from 'react-native';
import QRCodeScanner from 'react-native-qrcode-scanner';
import { useNavigation } from '@react-navigation/native';
import AES from 'crypto-js/aes';
import Utf8 from 'crypto-js/enc-utf8';
import { QR_PASSWORD } from '@env';
import is from 'is_js';
import haversine from 'haversine';
import * as Sentry from '@sentry/react-native';
// contexts
import ScanContext from 'contexts/scan-context';
import GpsContext from 'contexts/gps-context';
import AuthContext from 'contexts/gps-context';
// components
import Modal, {
  ModalIconHeader,
  ModalContent,
  ModalTitle,
  ModalText,
  ModalButtonContainer,
  ModalButton,
} from 'components/custom-modal';
import CameraZoomControl from './camera-zoom-control';
import Text from 'components/text';
import { getRevisitModalContent } from 'contexts/scan-context/get-checkout-modal-content';
// icons
import QrFrame from 'icons/qr-frame.svg';
// styles
import globalStyles from 'styles/global';
import styles from './revisit-page-content-styles';

//API
import { submitRv2gRevisit } from 'utils/api';
import { getCurrentAspDate, getTimezoneOffset } from 'utils/general';

const RevisitPageContent = () => {
  const navigation = useNavigation();

  const { checkIn, hideModal, revisitScan, currentUserSponsors } = useContext(ScanContext);

  const cameraRef = useRef();
  const [cameraZoom, setCameraZoom] = useState(0);

  const [isErrorModalVisible, setErrorModalVisible] = useState(false);
  const [errorModalMessage, setErrorModalMessage] = useState('');

  const [isRevisitModalOpen, setRevisitModalOpen] = useState(false);
  const [revisitModalMessage, setRevisitModalMessage] = useState('');
  const [modalType, setModalType] = useState('READY');
  const [currentSponsor, setCurrentSponsor] = useState({})

  const showErrorModal = (message) => {
    if (message) {
      setErrorModalMessage(message);
    }
    setErrorModalVisible(true);
  };
  const hideErrorModal = () => {
    setErrorModalVisible(false);
  };

  const { userLocation } = useContext(GpsContext);

  const validateSponsorTag = useCallback(
    (tagStr) => {
      try {
        const sponsorTag = JSON.parse(tagStr);
        if (
          !sponsorTag.hasOwnProperty('AccountID') ||
          typeof sponsorTag.AccountID !== 'number' ||
          !sponsorTag.hasOwnProperty('BannerID') ||
          typeof sponsorTag.BannerID !== 'number' ||
          !sponsorTag.hasOwnProperty('StoreID') ||
          typeof sponsorTag.StoreID !== 'number'||
          !sponsorTag.hasOwnProperty('City') ||
          typeof sponsorTag.City !== 'string' ||
          !sponsorTag.hasOwnProperty('Latitude') ||
          typeof sponsorTag.Latitude !== 'number' ||
          !sponsorTag.hasOwnProperty('Longitude') ||
          typeof sponsorTag.Longitude !== 'number' ||
          !sponsorTag.hasOwnProperty('State') ||
          typeof sponsorTag.State !== 'string' ||
          !sponsorTag.hasOwnProperty('SponsorID') ||
          typeof sponsorTag.SponsorID !== 'number' ||
          !sponsorTag.hasOwnProperty('StreetAddress') ||
          typeof sponsorTag.StreetAddress !== 'string'||
          !sponsorTag.hasOwnProperty('ZipCode') ||
          typeof sponsorTag.ZipCode !== 'string'
        ) {
          throw 'This is not a valid Revisit 2 Give store poster';
        }

        const radius = Math.max(5000, sponsorTag.Radius);
        if (
          is.existy(userLocation.latitude) &&
          is.existy(userLocation.longitude) &&
          haversine(
            userLocation,
            {
              latitude: sponsorTag.Latitude,
              longitude: sponsorTag.Longitude,
            },
            { unit: 'miles' }
          ) > radius
        ) {
          throw `You are not currently in range of this store. Please scan the QR code in the foyer of ${sponsorTag.StoreName}.`;
        }

        sponsorTag.Serial = `${sponsorTag.StoreCode}_${sponsorTag.SponsorID}`
        let matchingUserSponsor = currentUserSponsors.find((eachCurrentUserSponsor) =>
            sponsorTag.Serial === eachCurrentUserSponsor.Serial
        )
        console.log(currentUserSponsors, "my current user sponsors")
        if(!matchingUserSponsor) {

       //     if(matchingUserSponsor.LastUsed >== getCurrentAspDate() )
            return {
                  sponsorTag,
                  isValid: true,
                };
        } else {
          // console.log(matchingUserSponsor.LastUsed, "last time used matching user sponsor", getCurrentAspDate(), "my matching Usersponsors", getCurrentAspDate()+24*3600*1000)
            throw `You have already scanned this tag today! Please revisit with a sponsor you have not revisited today`
        }
      } catch (err) {
        return { isValid: false, error: err };
      }
    },
    [userLocation]
  );

  const attemptRevisit = useCallback(
    (codeEvent) => {
      if (codeEvent.type !== 'org.iso.QRCode' && codeEvent.type !== 'QR_CODE') {
        cameraRef.current.reactivate();
        return;
      }

      let sponsorJsonStr;

      try {
        try {
          const tagUrl = codeEvent.data;
          if (!tagUrl || !tagUrl.match(/https:\/\/revisit2give\.com/)) {
            throw 'This is not a valid QR code, please scan the QR code on a Revisit 2 Give poster.';
          }

          const sponsorCode = tagUrl.match(/store=(.+)/)[1];
          const sponsorJsonBytes = AES.decrypt(sponsorCode, QR_PASSWORD);
          sponsorJsonStr = sponsorJsonBytes.toString(Utf8);
        } catch (err) {
          console.log('Error decrypting RV2G store tag');
          throw 'This is not a valid QR code, please scan the QR code on a Revisit 2 Give poster.';
        }

        const parsedSponsorTag = validateSponsorTag(sponsorJsonStr);
        if (!parsedSponsorTag.isValid) {
          throw parsedSponsorTag.error;
        }
        const afterParseSponsorTag = parsedSponsorTag.sponsorTag
        if (parsedSponsorTag.sponsorTag.SponsorID == 0) {
        throw 'You have scanned a store tag. Please revisit our sponsors throughout the store and scan one of their codes to donate!'

        }
        parsedSponsorTag.sponsorTag.Sponsors.map(s => {
            if(s.SponsorID == parsedSponsorTag.sponsorTag.SponsorID){
                console.log(s, "my current sponsors")
                setCurrentSponsor(s)
                revisitScan(s, 'poster');
                showModal(parsedSponsorTag.sponsorTag.StoreName, s, "", "Revisit")
            }

        })
        console.log(parsedSponsorTag, "my parsed sponsor tag")

      } catch (err) {
        Sentry.captureMessage(err, {
          level: 'warning',
          extra: {
            qr_code_event: codeEvent,
            store_json_str: sponsorJsonStr,
            user_location: userLocation,
          },
        });
        console.log('error revisiting in', err);
        const errToDisplay =
          typeof err === 'string'
            ? err
            : 'There was an issue scanning the poster, please try again';
        showErrorModal(errToDisplay);
        return;
      }
    },

    [checkIn, navigation, userLocation, validateSponsorTag]
  );

// Modal functions for revisit modal
 const showModal = (store, sponsor, message, type) => {
 //console.log("in revisit page show modal", store, "store", sponsor)
  message = getRevisitModalContent(
    store,
    sponsor)
    setModalType("CONGRATS")
  setRevisitModalMessage(message);
  setRevisitModalOpen(true);
  };

  const onScan = (e) => {
    attemptRevisit(e);
  };

   const revisitAgain = () => {
      navigation.push('RevisitScreen')
      setRevisitModalOpen(false)
   }

   const goHome = () => {
        navigation.push('HomeStack')
         setRevisitModalOpen(false)
   }

  return (
    <View>
      <QRCodeScanner
        ref={cameraRef}
        onRead={onScan}
        fadeIn={false}
        showMarker={true}
        customMarker={<QrFrame width={500} height={500} />}
        cameraProps={{
          zoom: cameraZoom,
          maxZoom: 5,
        }}
        reactivateTimeout={150}
      />
      <View style={styles.bottomContainer}>
        <CameraZoomControl
          setCameraZoom={setCameraZoom}
          cameraZoom={cameraZoom}
        />
        <Text
          style={[
            globalStyles.normalFontSize,
            globalStyles.regularFont,
            styles.bottomText,
          ]}
        >
          Scan the QR code to Revisit our Sponsor!
        </Text>
      </View>
      <Modal isVisible={isErrorModalVisible}>
        <ModalIconHeader color="red" name="x-circle" />
        <ModalContent>
          <ModalTitle>Sorry</ModalTitle>
          <ModalText>{errorModalMessage}</ModalText>
        </ModalContent>
        <ModalButtonContainer>
          <ModalButton
            onPress={() => {
              cameraRef.current.reactivate();
              hideErrorModal();
            }}
          >
            OK
          </ModalButton>
        </ModalButtonContainer>
      </Modal>
            <Modal isVisible={isRevisitModalOpen}
            showFireworks={modalType === 'CONGRATS'}>
                    <ModalIconHeader color="green" name="check-circle" />
                    <ModalContent>
                      <ModalTitle>Thank You for Revisiting {currentSponsor.SponsorName}!</ModalTitle>
                      {revisitModalMessage}
                    </ModalContent>
                    <ModalButtonContainer>
                        <ModalButton color="green" onPress={goHome}>
                                All Done
                        </ModalButton>
                   <ModalButton color="green" onPress={revisitAgain}>
                      Revisit another Sponsor
                   </ModalButton>
                   </ModalButtonContainer>
            </Modal>
                </View>
  );
};

export default RevisitPageContent;

Build details?

package-json: "react-native-permissions": "^3.0.0", "react-native-qrcode-scanner": "^1.4.1", "react-native-camera": "^3.40.0",

tigerjiang commented 1 year ago

@cmd08010 Can you share your code? Maybe I can debug it for you.