Camera is not opening in react-native- iOS

69 views Asked by At

I want to open camera and scan QR code. But I am getting black screen in iOS instead of camera.

My code-

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { RNCamera } from 'react-native-camera';
import { request, PERMISSIONS, check, RESULTS } from 'react-native-permissions';
import axios from 'axios';
import Toast from 'react-native-simple-toast';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { API_DOMAIN, GET_EVENT_DETAILS } from '../../components/apiConstants';

const CheckedIn = ({ navigation, route }) => {
  const [isCheckedIn, setIsCheckedIn] = useState(false);
  const [checkInMessage, setCheckInMessage] = useState('');
  const [eQRstring, setEQRstring] = useState('');

  useEffect(() => {
    fetchQRString();
  }, []);

  const fetchQRString = async () => {
    try {
      const storedEvent = await AsyncStorage.getItem('selectedSeminar');
      const selectedSeminar = JSON.parse(storedEvent);
                const eventID = selectedSeminar.eid;
      const pocid = await AsyncStorage.getItem('pocid');

      const response = await axios.get(
        `${API_DOMAIN}${GET_EVENT_DETAILS}?eid=${eventID}&poid=${pocid}`
      );

      console.log(response.data.data.eQRstring);
      if (response.data.data.eQRstring) {
        const qrString = response.data.data.eQRstring;
        setEQRstring(qrString);
        console.log('QR String:', qrString);
        //navigation.navigate('CheckedIn', { qrString });
      } else {
        console.error('eQRstring is undefined in the response data');
      }
    } catch (error) {
      console.error('Error fetching QR string:', error);
    }
  };

  const handleScanSuccess = async (event) => {
    try {
      const scannedStringData = event.data.trim();
      console.log('Scanned Data:', scannedStringData);
      console.log('Expected QR String:', eQRstring);

      if (scannedStringData === eQRstring) {
        // Your existing logic for successful QR code match and check-in...
        Toast.show('Check-in Successful!', Toast.SHORT);
        navigation.navigate('HomeScreen');
      } else {
        setCheckInMessage('Invalid QR code');
        console.log('Invalid QR code');
        Toast.show('Invalid QR code!', Toast.SHORT);
        navigation.navigate('HomeScreen');
      }
    } catch (error) {
      setCheckInMessage('Error handling scan');
      console.error('Error handling scan:', error);
    }
  };

  const requestCameraPermission = async () => {
    const result = await check(PERMISSIONS.IOS.CAMERA);

    if(result === RESULTS.GRANTED){
      console.log('Camera permission granted');
    }
    else{
      const permissionResult = await request(PERMISSIONS.IOS.CAMERA);
      if (permissionResult !== 'granted') {
        console.error('Camera permission denied');
      }
      else{
        console.log('Camera permissions granted');
      }
    }
  };

  useEffect(() => {
    requestCameraPermission();
  }, []);

  const renderQRCodeScanner = () => {
    console.log('Rendering QR Code Scanner');
    return (
      <RNCamera
        style={styles.cameraStyle}
        onRead={handleScanSuccess}
        onCameraReady={()=> console.log('Camera is ready')}
        showMarker={true}
        markerStyle={styles.markerStyle}
        captureAudio={false}
        ratio='16:9'
      />
    );
  };

  return (
    <View style={styles.container}>
      {isCheckedIn ? (
        <Text style={styles.text}>Checked In!</Text>
      ) : (
        <>
          {renderQRCodeScanner()}
          {checkInMessage ? (
            <Text style={styles.message}>{checkInMessage}</Text>
          ) : null}
        </>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  cameraStyle: {
    flex: 1,
    borderWidth: 1,
    backgroundColor: 'red',
    justifyContent: 'center',
    alignItems: 'center',
  },
  markerStyle: {
    borderColor: 'red',
    borderRadius: 10,
  },
  text: {
    fontSize: 24,
    fontWeight: 'bold',
    color: 'green',
  },
  message: {
    fontSize: 16,
    color: 'red',
    marginTop: 20,
  },
});

export default CheckedIn;

I am getting request for permission. But instead of opening camera, I am getting white blank screen without any errors or warnings.

I also gave permission in Info.plist-

<key>NSCameraUsageDescription</key>
<string>We need access to your camera to scan QR codes.</string>

My Log-

LOG QR String: 1688236200

LOG Camera permission granted

1

There are 1 answers

0
famfamfam On

react-native-camera were deprecated, please use react-native-vision-camera instead