Building an iOS Feature with Expo, Compared to the Xcode Workflow

After this chapter you will be able to build the same feature twice - capture a photo and save it to the device’s photo library - once with Expo and once with native Xcode, and see exactly where the two workflows differ. You will know which steps Expo removes, which steps it merely relocates, and how the permission story changes on each platform.

The feature

One screen with a camera preview, a shutter button, and a small thumbnail of the photo that was just captured. Tapping the shutter takes the picture and writes it into the system’s photo library so that the user can find it in the Photos app.

It is a deliberately ordinary feature: camera access, a permission prompt, and a write to the photo library. Almost every real application has something like it, which makes it a fair test of the two toolchains.

The Expo implementation

Step 1: create the project

npx create-expo-app@latest camera-demo
cd camera-demo

Step 2: install the modules

# expo install picks the version that matches your SDK.
npx expo install expo-camera expo-media-library

Step 3: describe the permissions in the configuration

The permission prompts are declared once, in the configuration file, and the config plugin writes them into the generated Info.plist.

{
  "expo": {
    "name": "Camera Demo",
    "slug": "camera-demo",
    "ios": {
      "bundleIdentifier": "com.example.camerademo",
      "infoPlist": {
        "NSCameraUsageDescription": "Camera Demo uses the camera to photograph equipment.",
        "NSPhotoLibraryAddUsageDescription": "Camera Demo saves the photos you take to your library."
      }
    }
  }
}

Step 4: write the screen

import { useRef, useState } from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';
import { CameraView, useCameraPermissions } from 'expo-camera';
import * as MediaLibrary from 'expo-media-library';

export default function CameraScreen() {
  const cameraRef = useRef(null);
  const [permission, requestPermission] = useCameraPermissions();
  const [status, setStatus] = useState('');

  async function takePhoto() {
    const photo = await cameraRef.current.takePictureAsync({ quality: 0.8 });
    if (!photo?.uri) return;

    const libraryPermission = await MediaLibrary.requestPermissionsAsync();
    if (!libraryPermission.granted) {
      setStatus('The photo was taken but could not be saved to your library.');
      return;
    }

    await MediaLibrary.saveToLibraryAsync(photo.uri);
    setStatus('Saved to your photo library.');
  }

  if (!permission) return null;

  if (!permission.granted) {
    return (
      <View style={styles.container}>
        <Text>Camera access is needed to take a photo.</Text>
        <Button title="Allow camera" onPress={requestPermission} />
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <CameraView ref={cameraRef} style={StyleSheet.absoluteFill} facing="back" />
      <View style={styles.controls}>
        <Text style={styles.status}>{status}</Text>
        <Button title="Take photo" onPress={takePhoto} />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#000000' },
  controls: { padding: 24, alignItems: 'center' },
  status: { color: '#ffffff', marginBottom: 12 },
});

Step 5: run it

npx expo start

The camera module contains native code, so Expo Go cannot run it. Press i for the simulator, or build a development client for a physical device.

Build it with npx expo run:ios, which compiles the native project, installs it on the simulator or a connected device and starts the bundler.

The native implementation

The same feature in Swift, in an Xcode project, starts with the permissions.

Step 1: add the usage descriptions

In the target’s Info.plist, add the two keys iOS requires:

<key>NSCameraUsageDescription</key>
<string>Camera Demo uses the camera to photograph equipment.</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Camera Demo saves the photos you take to your library.</string>

Xcode also shows the same keys in the target settings under Info, so you can type them in the GUI instead of editing the file.

Step 2: request the permission at runtime

import AVFoundation

private func requestAccessIfNeeded() {
    switch AVCaptureDevice.authorizationStatus(for: .video) {
    case .authorized:
        configureSession()
    case .notDetermined:
        AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
            DispatchQueue.main.async {
                granted ? self?.configureSession() : self?.showDeniedMessage()
            }
        }
    default:
        showDeniedMessage()
    }
}

Step 3: capture the photo

import UIKit

extension CameraViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    @objc private func didTapShutter() {
        guard UIImagePickerController.isSourceTypeAvailable(.camera) else { return }

        let picker = UIImagePickerController()
        picker.sourceType = .camera
        picker.delegate = self
        present(picker, animated: true)
    }

    func imagePickerController(
        _ picker: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]
    ) {
        picker.dismiss(animated: true)

        guard let image = info[.originalImage] as? UIImage,
              let data = image.jpegData(compressionQuality: 0.8) else { return }

        saveToPhotoLibrary(data)
    }
}

Step 4: save to the photo library

import Photos

private func saveToPhotoLibrary(_ data: Data) {
    PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in
        guard status == .authorized || status == .limited else { return }

        PHPhotoLibrary.shared().performChanges {
            let request = PHAssetCreationRequest.forAsset()
            request.addResource(with: .photo, data: data, options: nil)
        } completionHandler: { success, error in
            DispatchQueue.main.async {
                // Report the result to the user.
            }
        }
    }
}

That is the whole native implementation: roughly a hundred lines, one view controller, one delegate, and an Info.plist edit.

Side by side

StepNative XcodeExpo
Start a projectCreate an app target in Xcode, choose a templatenpx create-expo-app@latest
Declare permissionsEdit Info.plist or the target settingsDeclare the keys in app.json, or pass them to a config plugin
Add the cameraWrite an AVCaptureSession setup, or use UIImagePickerControllernpx expo install expo-camera, then render CameraView
Request permissionAVCaptureDevice.requestAccess, handle three statesuseCameraPermissions, which returns the permission and a request function
Capture the photoUIImagePickerController delegate callbacktakePictureAsync on a CameraView ref
Save to the libraryPHPhotoLibrary.performChangesMediaLibrary.saveToLibraryAsync
Preview the resultA UIImageView you configureA Text or Image bound to the returned URI
Iterate on the interfaceRecompile and relaunchFast Refresh
Ship itArchive, validate, uploadeas build and eas submit

What really changed

Three things are genuinely faster with Expo:

  1. The permission and configuration plumbing is declared, not written. The usage strings, the bundle identifier and the module wiring live in one file that can be read at a glance.
  2. The camera is a component, not a subsystem. CameraView is markup. The native version is a session, a delegate, a presentation call and a dismissal call.
  3. The iteration loop is shorter for the JavaScript half of the app, which in a modern app is most of it.

Two things are not faster:

  1. The build. An Expo app that contains native modules still has to be compiled and linked. In a local development build that is the same work Xcode does.
  2. Anything you write natively. If the camera preview has to be frame-perfect, or the photo must be captured at a specific shutter speed, you are back to AVCaptureSession and the Expo advantage for that piece of work is zero.

A note on the picker alternative

If the camera preview itself is not the point, expo-image-picker is even shorter: it presents the system picker and hands you a URI, with the same permission model and no preview view to build.

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

const result = await ImagePicker.launchCameraAsync({
  mediaTypes: ['images'],
  quality: 0.8,
});

if (!result.canceled) {
  await ImageLibrary.saveToLibraryAsync(result.assets[0].uri);
}

The trade-off is the same one every native app makes: the system picker is less code, while a custom preview is more control.

Practice

The product team now wants the same screen to offer a “from the library” option next to “take a photo”, and to show a thumbnail of the last three photos. Describe the change in the Expo implementation and in the native implementation, and say which parts of the Expo version would change if you switched to expo-image-picker instead of expo-camera.

Expoexpo-cameraexpo-media-libraryPermissionsImage Picker

Approach:

The change is mostly about permissions and about the source of the image, not about the camera code. The key insight is that the two permissions are different: the camera needs NSCameraUsageDescription, while the library needs read access to show the last three photos and write access to save new ones. Getting the permission set right is most of the work.

Steps:

  1. Add the library read permission. The Expo configuration needs NSPhotoLibraryUsageDescription in addition to the two keys that are already there. The native version needs the same key added to Info.plist and a PHPhotoLibrary.requestAuthorization(for: .readWrite) call at start-up.
  2. Add the photo library button. In Expo this is a second Button that calls ImagePicker.launchImageLibraryAsync, or, if the camera preview stays, it opens the system picker over the existing preview. In the native version it is a second action that presents UIImagePickerController with sourceType = .photoLibrary.
  3. Handle the two permission prompts separately. The camera permission and the library permission are independent, and the user can grant one and refuse the other. The UI must therefore show the shutter button and the library button under different permission states rather than hiding the whole screen.
  4. Show the last three photos. Read the most recent assets from the library. In Expo that is MediaLibrary.getAssetsAsync with a limit of three, ordered by creation date, and the permission has to be read access, not write-only. In the native version it is PHAsset.fetchAssets with a sort descriptor on creation date and a limit of three, which returns PHAsset objects whose images you request with the image manager.
  5. Note what changes with expo-image-picker. The camera preview disappears, because expo-image-picker presents the system camera and returns a URI. CameraView, the camera ref and takePictureAsync all go away, and the permission request becomes ImagePicker.requestCameraPermissionsAsync. The saving code does not change, because both paths end with a URI that MediaLibrary.saveToLibraryAsync accepts.

Answer:

import { useRef, useState, useEffect } from 'react';
import { Button, Image, StyleSheet, Text, View } from 'react-native';
import { CameraView, useCameraPermissions } from 'expo-camera';
import * as ImagePicker from 'expo-image-picker';
import * as MediaLibrary from 'expo-media-library';

export default function CameraScreen() {
  const cameraRef = useRef(null);
  const [cameraPermission, requestCameraPermission] = useCameraPermissions();
  const [libraryPermission, requestLibraryPermission] =
    MediaLibrary.usePermissions();
  const [recent, setRecent] = useState([]);

  async function loadRecent() {
    if (!libraryPermission?.granted) return;
    const assets = await MediaLibrary.getAssetsAsync({ first: 3 });
    setRecent(assets.assets.map((asset) => asset.uri));
  }

  useEffect(() => { loadRecent(); }, [libraryPermission?.granted]);

  async function takePhoto() {
    const photo = await cameraRef.current.takePictureAsync({ quality: 0.8 });
    if (!photo?.uri) return;
    await MediaLibrary.saveToLibraryAsync(photo.uri);
    loadRecent();
  }

  async function pickFromLibrary() {
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      quality: 0.8,
    });
    if (result.canceled) return;
    await MediaLibrary.saveToLibraryAsync(result.assets[0].uri);
    loadRecent();
  }

  return (
    <View style={styles.container}>
      {cameraPermission?.granted ? (
        <CameraView ref={cameraRef} style={StyleSheet.absoluteFill} facing="back" />
      ) : (
        <View style={styles.placeholder}>
          <Text>Camera access is needed to take a photo.</Text>
          <Button title="Allow camera" onPress={requestCameraPermission} />
        </View>
      )}

      <View style={styles.thumbnails}>
        {recent.map((uri) => (
          <Image key={uri} source={{ uri }} style={styles.thumbnail} />
        ))}
      </View>

      <View style={styles.controls}>
        {!libraryPermission?.granted ? (
          <Button title="Allow access to your photos" onPress={requestLibraryPermission} />
        ) : (
          <>
            <Button title="Take photo" onPress={takePhoto} />
            <Button title="From library" onPress={pickFromLibrary} />
          </>
        )}
      </View>
    </View>
  );
}

The native equivalent follows the same shape: AVCaptureDevice.requestAccess for the camera and PHPhotoLibrary.requestAuthorization(for: .readWrite) for the library, two separate UI states, a second UIImagePickerController configured with .photoLibrary, and a PHAsset.fetchAssets query with a creation-date sort descriptor and a limit of three to fill the thumbnail row.

Found an issue with this content?

Tell us what could be improved.