A Step-by-Step Guide to React Native Vision Camera

React Native-built iOS and Android apps are increasingly needing their cameras to be configured. We will cover every aspect of React Native Vision Camera in this blog, including its features that pertain to QR codes.

React Native Vision Camera: What Is It?

Nowadays, more and more people use the cameras on their smartphones in apps. For instance, you may access a QR code at a restaurant to view the menu (many businesses no longer offer paper menus). The same holds true for adding a function that allows users to pay by scanning a barcode.

Both scenarios are now popular. Do you, however, understand how to code this feature for a React Native application? You should first be aware of what the React Native Vision Camera is. It basically functions as a QR code scanner app and often requires the following components: Both scenarios are now commonplace. Do you, however, understand how to code this feature for a React Native application? You should first be aware of what the React Native Vision Camera is. It basically functions as a QR code scanner app and often requires the following components:

  • Photos
  • Face detection
  • Bar code scanning
  • Text recognition
  • Videos

Installation

In your React Native app, install the package by using the following command:

npm install react-native-vision-camera

If developing for iOS, further you have to do pod install for the same:

cd ios && pod install

Updating manifests

Next, you need to ask for permission to use the camera and microphone, this is done in different ways for Android and iOS.

For Android, you will have to add the following lines to AndroidManifest.xml inside the <manifest> tag to allow the app to request for camera and microphone:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

For iOS, you will have to add the following lines to Info.plist file inside the outermost <dict> tag to allow the app to request for camera and microphone: 

<key>NSCameraUsageDescription</key>
<string>$(PRODUCT_NAME) needs access to your Camera.</string>
<key>NSMicrophoneUsageDescription</key>
<string>$(PRODUCT_NAME) needs access to your Microphone.</string>

Getting/Requesting Permissions

VisionCamera also provides functions to easily get and request Microphone and Camera permissions.

Getting Permissions

Simply use the get functions to find out if a user has granted or denied permission before:

const cameraPermission = await Camera.getCameraPermissionStatus()
const microphonePermission = await Camera.getMicrophonePermissionStatus()

A permission status can have the following values:

  • authorized: Your app is authorized to use said permission. Continue with using the <Camera> view.
  • not-determined: Your app has not yet requested permission from the user. Continue by calling the request functions.
  • denied: Your app has already requested permissions from the user, but was explicitly denied. You cannot use the request functions again, but you can use the Linking API to redirect the user to the Settings App, where he can manually grant the permission.
  • restricted: (iOS only) Your app cannot use the Camera or Microphone because that functionality has been restricted, possibly due to active restrictions such as parental controls being in place.

Requesting Permissions

Use the request functions to prompt the user to give your app permission to use the Camera or Microphone.

NOTE: The request functions only have effect if the current permission status is not-determined.

const newCameraPermission = await Camera.requestCameraPermission()
const newMicrophonePermission = await Camera.requestMicrophonePermission()

The permission request status can have the following values:

  • authorized: Your app is authorized to use said permission. Continue with using the <Camera> view.
  • denied: The user explicitly denied the permission request alert. You cannot use the request functions again, but you can use the Linking API to redirect the user to the Settings App where he can manually grant the permission.
  • restricted: (iOS only) Your app cannot use the Camera or Microphone because that functionality has been restricted, possibly due to active restrictions such as parental controls being in place.

Using the Camera

To keep the camera away from re-renders due to permissions, it’s always a good idea to ask for the permissions as soon as possible. Like, for example asking the permissions on the HomeScreen itself instead of asking in the CameraScreen. I hope you got what I am trying to convey.

So, in the HomeScreen of your App, add the following lines:

import {Camera} from 'react-native-vision-camera';
/* Inside your component */
const checkCameraPermission = async () => {
  let status = await Camera.getCameraPermissionStatus();
  if (status !== 'authorized') {
    await Camera.requestCameraPermission();
    status = await Camera.getCameraPermissionStatus();
    if (status === 'denied') {
      showToast(
        'You will not be able to scan if you do not allow camera access',
      );
    }
  }
};

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

Now add the following lines to your CameraScreen to capture photographs:

// All of your regular imports
import {useCameraDevices, Camera} from 'react-native-vision-camera';
// inside your component

const devices = useCameraDevices();
const device = devices.back;
const camera = useRef<Camera>(null)

const [hasPermission, setHasPermission] = React.useState(false);

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

 const checkCameraPermission = async () => {
    const status = await Camera.getCameraPermissionStatus();
    setHasPermission(status === 'authorized');
};

const photo = await camera.current.takePhoto({
  flash: 'on'
})

return(
  device != null &&
    hasPermission && (
      <>
        <StatusBar barStyle="light-content" backgroundColor="#000000" />
        <Camera
          style={StyleSheet.absoluteFill}
          device={device}
          ref={camera}
        />
      </>
    )
);


// Styles:
const styles = StyleSheet.create({
  rnholeView: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    alignSelf: 'center',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(0,0,0,0.5)',
  },
});

You can customize capture options such as automatic red-eye reduction, automatic image stabilization, combining images from constituent physical camera devices to create a single high quality fused image, enable flash, prioritize speed over quality and more using the options parameter. 

takePhoto returns a PhotoFile which contains a path property you can display in your App using an <Image> or <FastImage>.

I sincerely hope that the majority of you find the approach covered here to be helpful. Thank you for reading, and please feel free to leave any comments or questions in the comments section below.

Post a Comment

0 Comments