Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 38 ยท Native Modules and APIs

Camera, Image Picker and Permissions

Use expo-camera and expo-image-picker: request permissions correctly, handle denied and blocked states, take photos, pick from the library, scan barcodes and process results.

Device features such as the camera, photo library and location are protected by permissions: the operating system asks the user, and the user can say no. Handling "no" gracefully is as important as the feature itself. This lesson uses the camera and photo library to teach the permission flow that every Expo native API shares.

All the Expo modules here need a real device or simulator, so their code is read-only. The live stand-ins model the permission state machine and result handling.

Install and declare permissions

Terminal
npx expo install expo-camera expo-image-picker

Add the config plugins with the explanatory text iOS requires (Apple rejects apps whose purpose strings are missing or vague):

JSON
{
  "expo": {
    "plugins": [
      ["expo-camera", {
        "cameraPermission": "Trail Notes uses the camera to photograph trail signs.",
        "microphonePermission": false
      }],
      ["expo-image-picker", {
        "photosPermission": "Trail Notes lets you attach photos from your library."
      }]
    ]
  }
}

Plugin changes are native changes: rebuild your development build (Prebuild and Config Plugins).

The permission states

A permission response has a status (undetermined, granted, denied), a boolean granted, and canAskAgain. Understanding the combinations avoids dead ends:

Situation status canAskAgain What to do
Never asked undetermined true request it, ideally after explaining why
Allowed granted true proceed
Denied once denied true (Android) you can ask once more with context
Denied permanently denied false the OS will not show the dialog again: send the user to Settings
flowchart TD
  A["Feature needs camera"] --> B{"Permission status?"}
  B -- "granted" --> C["Show the camera"]
  B -- "undetermined" --> D["Explain, then request"]
  D --> B
  B -- "denied, canAskAgain" --> D
  B -- "denied, cannot ask again" --> E["Explain + button: Open Settings"]

Request with context; fall back to Settings when the OS refuses to ask again.

JS Permission flow, modeled

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Camera preview and taking a photo

expo-camera provides CameraView and the useCameraPermissions hook:

TSX
import { CameraView, useCameraPermissions } from 'expo-camera';
import { useRef, useState } from 'react';
import { Button, Linking, Text, View, Pressable } from 'react-native';
import { Image } from 'expo-image';

export default function CameraScreen() {
  const [permission, requestPermission] = useCameraPermissions();
  const [facing, setFacing] = useState<'back' | 'front'>('back');
  const [photoUri, setPhotoUri] = useState<string | null>(null);
  const camera = useRef<CameraView>(null);

  if (!permission) return <View />;                       // still loading

  if (!permission.granted) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', padding: 24, gap: 12 }}>
        <Text>We need the camera to photograph trail signs.</Text>
        {permission.canAskAgain
          ? <Button title="Allow camera" onPress={requestPermission} />
          : <Button title="Open Settings" onPress={() => Linking.openSettings()} />}
      </View>
    );
  }

  async function takePhoto() {
    const photo = await camera.current?.takePictureAsync({ quality: 0.7 });
    if (photo) setPhotoUri(photo.uri);
  }

  if (photoUri) return <Image source={{ uri: photoUri }} style={{ flex: 1 }} contentFit="cover" />;

  return (
    <View style={{ flex: 1 }}>
      <CameraView ref={camera} style={{ flex: 1 }} facing={facing} />
      <Pressable onPress={takePhoto}><Text>Take photo</Text></Pressable>
      <Pressable onPress={() => setFacing((f) => (f === 'back' ? 'front' : 'back'))}><Text>Flip</Text></Pressable>
    </View>
  );
}

CameraView has props for facing, flash ('on' | 'off' | 'auto'), zoom (0 to 1), mode ('picture' or 'video', with recordAsync) and torch. The camera does not work on most simulators (use a real device; Android emulators can use a virtual camera), and takePictureAsync returns an object with a cache uri, width, height and optional base64.

Scanning barcodes and QR codes

TSX
<CameraView
  style={{ flex: 1 }}
  barcodeScannerSettings={{ barcodeTypes: ['qr', 'ean13'] }}
  onBarcodeScanned={scanned ? undefined : ({ data, type }) => { setScanned(true); handle(data); }}
/>

Set a scanned flag after the first hit, otherwise the callback fires many times per second. Treat scanned data as untrusted input: validate it before opening URLs or acting on it.

JS Validate a scanned code

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Picking from the library or camera

expo-image-picker uses the system picker. On modern iOS and Android the photo picker needs no library permission to select images (the system hands you only the chosen ones); the camera option still needs camera permission.

TSX
import * as ImagePicker from 'expo-image-picker';

async function pickImages() {
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ['images'],            // 'videos' and 'livePhotos' also exist
    allowsMultipleSelection: true,
    selectionLimit: 4,
    quality: 0.8,                      // compression, 0 to 1
    allowsEditing: false,              // cropping UI works for single selection
  });
  if (result.canceled) return [];      // user dismissed the picker
  return result.assets.map((a) => ({ uri: a.uri, width: a.width, height: a.height, mime: a.mimeType }));
}

async function takeWithCamera() {
  const perm = await ImagePicker.requestCameraPermissionsAsync();
  if (!perm.granted) return null;
  const result = await ImagePicker.launchCameraAsync({ quality: 0.8 });
  return result.canceled ? null : result.assets[0];
}

Always check result.canceled first; assets is null when cancelled. Results are copies in the cache directory, so move or upload what you want to keep (File System and Sharing).

JS Handle a picker result

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Good permission manners

  • Ask in context, when the user taps the feature, not at app launch.
  • Explain first with your own screen; the OS dialog allows only one chance on iOS.
  • Offer a fallback (pick a photo instead of using the camera) when permission is denied.
  • Ask for the least (the photo picker instead of full library access).
  • Provide accurate purpose strings; vague ones get rejected in review.

Common mistakes

  • Calling the camera before the permission is granted, getting a blank view.
  • Ignoring canAskAgain, leaving users stuck after a denial.
  • Not checking canceled, then crashing on assets[0].
  • Uploading full-resolution photos on mobile data; resize and compress first.
  • Testing only on simulators, which have no real camera.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user denied the camera permission and canAskAgain is false. What should your app do?

    The system will not show the dialog again, so only Settings can change the decision.
  2. 2. What should you check first after launchImageLibraryAsync resolves?

    When the user cancels, assets is null.
  3. 3. Why does a QR scan handler usually set a scanned flag?

    Without a guard the callback runs many times per second.
  4. 4. Why does the config include cameraPermission text?

    The plugin writes NSCameraUsageDescription, which Apple shows in the permission dialog.

Summary

  • Every device API follows a permission flow: check status, request with context, handle denied and blocked states.
  • CameraView shows a live preview, takes photos and scans barcodes; the image picker selects media and returns assets.
  • Always check canceled, validate scanned data and resize large images.
  • Permission strings and plugin options are native config: rebuild after changing them.

Next: Location and Maps