Get started
Introduction
Installation
Your first app
Tutorials
Fission tutorials
Capture iPhone photos and use the flashlight in a Rust app
Core concepts
Components
State and effects
Protected routes
Server-side rendering
Styling
Testing
Deployment
Reference
API reference
Cookbook
Fission 0.16.0
Documentation version
Read the changelog →

Capture iPhone photos and use the flashlight in a Rust app

Capture an actual delivery image, retain its reference and use a reported torch without losing the receiving draft on failure.
iOS

What you will build

Prepare a review from the user's delivery reference, note and actual image whilst keeping supplier submission outside this session-local workflow.
Snapshot the delivery reference before requesting a real capture
Consume and bound the image stream before presenting evidence
Use the selected camera's reported torch and distinguish its last confirmed state from telemetry
A supplier review needs the photograph which was actually taken, not a diagram which looks like evidence. It also needs to remain associated with the delivery it describes. If the clerk changes the reference whilst the camera is working, the returned image must not silently attach itself to a different shipment.
We will create a receiving draft from user input, capture a real photograph and prepare an in-memory review snapshot. For example, enter Riverbend Nursery's delivery reference and describe the crushed crates you are inspecting. The normal iOS app and browser preview start empty and support the same workflow; neither depends on a preview-only receipt.

Create the app and declare camera access

Complete iOS setup first.
cargo install cargo-fission
fission init ios-capture-photos-and-use-the-flashlight-on-ios
cd ios-capture-photos-and-use-the-flashlight-on-ios
fission add-target ios --project-dir .
fission add-capability camera --project-dir .
cargo add serde --features derive
cargo add serde_yaml
Inspect platforms/ios/Info.plist and replace the generic NSCameraUsageDescription with an accurate purpose. Declaring the capability does not make that explanation product-specific. Keep Fission's generated src/main.rs; the shared library below supplies its actual app.

Run the finished example

fission run --target ios --project-dir .

1. Capture and consume the real image

The permission response, camera features, capture result and image bytes are different stages. Every completion is a bound unit action which decodes actual input. The job consumes the one-shot stream asynchronously and applies explicit byte, dimension and MIME limits. A failed replacement leaves the previous photograph intact.
The delivery reference is captured when the request starts. Preparing a review requires that the current reference matches the photograph's reference. The review is a snapshot of the actual note and image, so editing the draft later does not rewrite a review already prepared.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/app/jobs.rs","value":"src-app-jobs-rs"},{"index":2,"label":"src/app/state.rs","value":"src-app-state-rs"},{"index":3,"label":"src/app/screen.rs","value":"src-app-screen-rs"},{"index":4,"label":"src/i18n.rs","value":"src-i18n-rs"},{"index":5,"label":"src/lib.rs","value":"src-lib-rs"},{"index":6,"label":"preview/lib.rs","value":"preview-lib-rs"},{"index":7,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":8,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
pub mod jobs;
mod screen;
pub mod state;
pub use screen::ReceivingScreen;
pub use state::ReceivingState;
{"id":"fission-tabs-1","index":1,"label":"src/app/jobs.rs","value":"src-app-jobs-rs"}
use fission::core::{CameraCapture, JobCtx, JobRef, JobSpec};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PhotoRequest {
    pub reference: String,
    pub capture: CameraCapture,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArrivalPhoto {
    pub reference: String,
    pub bytes: Vec<u8>,
    pub content_type: String,
}
pub struct CollectPhoto;
impl JobSpec for CollectPhoto {
    type Request = PhotoRequest;
    type Ok = ArrivalPhoto;
    type Err = String;
    const NAME: &'static str = "receiving.collect-photo";
}
pub const COLLECT_PHOTO: JobRef<CollectPhoto> = JobRef::new(CollectPhoto::NAME);

pub async fn collect_photo(request: PhotoRequest, cx: JobCtx) -> Result<ArrivalPhoto, String> {
    let mut stream = cx
        .open_data_stream(request.capture.stream)
        .map_err(|error| error.to_string())?;
    // Consume the one-shot handle even when its metadata fails these bounds.
    let pixels = u64::from(request.capture.width) * u64::from(request.capture.height);
    if pixels == 0 || pixels > 16_000_000 {
        return Err("Unsupported image dimensions".into());
    }
    if !matches!(
        request.capture.content_type.as_str(),
        "image/jpeg" | "image/png"
    ) {
        return Err("Only JPEG and PNG arrival photos are accepted".into());
    }
    let mut bytes = Vec::new();
    while let Some(chunk) = std::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await {
        let chunk = chunk.map_err(|error| error.to_string())?;
        let length = bytes
            .len()
            .checked_add(chunk.len())
            .ok_or("Image is too large")?;
        if length > 8 * 1024 * 1024 {
            return Err("Image exceeds the eight-MiB limit".into());
        }
        bytes.extend_from_slice(&chunk);
    }
    if bytes.is_empty() {
        return Err("The camera returned an empty image".into());
    }
    Ok(ArrivalPhoto {
        reference: request.reference,
        bytes,
        content_type: request.capture.content_type,
    })
}
{"id":"fission-tabs-1","index":2,"label":"src/app/state.rs","value":"src-app-state-rs"}
use super::jobs::{ArrivalPhoto, PhotoRequest, COLLECT_PHOTO};
use fission::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReviewSnapshot {
    pub reference: String,
    pub note: String,
    pub photo: ArrivalPhoto,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReceivingState {
    pub locale: Locale,
    pub reference: String,
    pub note: String,
    pub busy: bool,
    pub status_key: String,
    pub error: Option<String>,
    pub device: Option<CameraDevice>,
    pub photo: Option<ArrivalPhoto>,
    pub capture_reference: Option<String>,
    pub torch_on: bool,
    pub torch_requested: Option<bool>,
    pub review: Option<ReviewSnapshot>,
}
impl Default for ReceivingState {
    fn default() -> Self {
        Self {
            locale: Locale::from("en-US"),
            reference: String::new(),
            note: String::new(),
            busy: false,
            status_key: "receiving.ready".into(),
            error: None,
            device: None,
            photo: None,
            capture_reference: None,
            torch_on: false,
            torch_requested: None,
            review: None,
        }
    }
}
impl GlobalState for ReceivingState {}

fn unexpected(state: &mut ReceivingState) {
    state.busy = false;
    state.capture_reference = None;
    state.torch_requested = None;
    state.status_key = "receiving.unexpected".into();
}

pub fn check_camera(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    if state.busy || state.torch_on {
        return;
    }
    state.busy = true;
    state.error = None;
    state.status_key = "receiving.permission_pending".into();
    let ok = cx
        .effects
        .bind(PermissionReturned, reduce_with!(permission_returned));
    let err = cx.effects.bind(CameraFailed, reduce_with!(camera_failed));
    cx.effects
        .camera()
        .request_permission(CameraPermissionRequest { reason: None })
        .on_ok(ok)
        .on_err(err);
}

#[fission_reducer(PermissionReturned)]
fn permission_returned(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    match cx.input.capability_ok(REQUEST_CAMERA_PERMISSION) {
        Some(CameraPermission::Granted) => {
            state.status_key = "receiving.features_pending".into();
            let ok = cx
                .effects
                .bind(FeaturesReturned, reduce_with!(features_returned));
            let err = cx.effects.bind(CameraFailed, reduce_with!(camera_failed));
            cx.effects.camera().availability().on_ok(ok).on_err(err);
        }
        Some(CameraPermission::Denied | CameraPermission::Restricted) => {
            state.busy = false;
            state.device = None;
            state.status_key = "receiving.denied".into();
        }
        Some(CameraPermission::Unknown) => {
            state.busy = false;
            state.device = None;
            state.status_key = "receiving.unknown".into();
        }
        None => unexpected(state),
    }
}

#[fission_reducer(FeaturesReturned)]
fn features_returned(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    let Some(features) = cx.input.capability_ok(GET_CAMERA_AVAILABILITY) else {
        unexpected(state);
        return;
    };
    state.busy = false;
    if features.permission != CameraPermission::Granted {
        state.device = None;
        state.status_key = "receiving.denied".into();
        return;
    }
    state.device = features
        .devices
        .iter()
        .find(|device| device.facing == CameraFacing::Back)
        .or_else(|| features.devices.first())
        .cloned();
    state.status_key = if state.device.is_some() {
        "receiving.camera_ready"
    } else {
        "receiving.unavailable"
    }
    .into();
}

pub fn capture(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    if state.busy || state.reference.trim().is_empty() {
        return;
    }
    let Some(device) = state.device.clone() else {
        return;
    };
    state.capture_reference = Some(state.reference.trim().to_owned());
    state.busy = true;
    state.error = None;
    state.status_key = "receiving.capture_pending".into();
    let ok = cx.effects.bind(Captured, reduce_with!(captured));
    let err = cx.effects.bind(CameraFailed, reduce_with!(camera_failed));
    cx.effects
        .camera()
        .capture_photo(CameraCaptureRequest {
            camera_id: Some(device.id),
            facing: device.facing,
            resolution: Some(CameraResolution {
                width: 1600,
                height: 1200,
            }),
            format: CameraImageFormat::Jpeg,
            flash: CameraFlashMode::Off,
            quality: Some(88),
        })
        .on_ok(ok)
        .on_err(err);
}

#[fission_reducer(Captured)]
fn captured(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    let Some(capture) = cx.input.capability_ok(CAPTURE_PHOTO) else {
        unexpected(state);
        return;
    };
    let Some(reference) = state.capture_reference.take() else {
        unexpected(state);
        return;
    };
    state.status_key = "receiving.image_pending".into();
    let ok = cx
        .effects
        .bind(PhotoCollected, reduce_with!(photo_collected));
    let err = cx.effects.bind(PhotoFailed, reduce_with!(photo_failed));
    cx.effects
        .app(COLLECT_PHOTO, PhotoRequest { reference, capture })
        .on_ok(ok)
        .on_err(err);
}

#[fission_reducer(PhotoCollected)]
fn photo_collected(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    state.busy = false;
    match cx.input.job_ok(COLLECT_PHOTO) {
        Some(photo) => {
            state.photo = Some(photo);
            state.status_key = "receiving.attached".into();
        }
        None => unexpected(state),
    }
}

#[fission_reducer(PhotoFailed)]
fn photo_failed(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    state.busy = false;
    state.status_key = "receiving.failed".into();
    state.error = cx.input.job_err(COLLECT_PHOTO);
    if state.error.is_none() {
        unexpected(state);
    }
}

pub fn toggle_torch(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    if state.busy {
        return;
    }
    let Some(device) = state.device.as_ref().filter(|device| device.has_flashlight) else {
        return;
    };
    let request = CameraFlashlightRequest {
        camera_id: Some(device.id.clone()),
        enabled: !state.torch_on,
        intensity: None,
    };
    state.torch_requested = Some(request.enabled);
    state.busy = true;
    state.error = None;
    state.status_key = "receiving.torch_pending".into();
    let ok = cx.effects.bind(TorchChanged, reduce_with!(torch_changed));
    let err = cx.effects.bind(CameraFailed, reduce_with!(camera_failed));
    cx.effects
        .camera()
        .set_flashlight(request)
        .on_ok(ok)
        .on_err(err);
}

#[fission_reducer(TorchChanged)]
fn torch_changed(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    state.busy = false;
    match (
        cx.input.capability_ok(SET_CAMERA_FLASHLIGHT),
        state.torch_requested.take(),
    ) {
        (Some(()), Some(enabled)) => {
            state.torch_on = enabled;
            state.status_key = "receiving.torch_changed".into();
        }
        _ => unexpected(state),
    }
}

#[fission_reducer(CameraFailed)]
fn camera_failed(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    state.busy = false;
    state.capture_reference = None;
    state.torch_requested = None;
    let error = cx
        .input
        .capability_error(REQUEST_CAMERA_PERMISSION)
        .or_else(|| cx.input.capability_error(GET_CAMERA_AVAILABILITY))
        .or_else(|| cx.input.capability_error(CAPTURE_PHOTO))
        .or_else(|| cx.input.capability_error(SET_CAMERA_FLASHLIGHT));
    match error {
        Some(error) => {
            state.status_key = if error.code == "unsupported" {
                "receiving.unavailable"
            } else {
                "receiving.failed"
            }
            .into();
            state.error = Some(format!("{}: {}", error.code, error.message));
        }
        None => unexpected(state),
    }
}

pub fn prepare_review(state: &mut ReceivingState) {
    if state.busy {
        return;
    }
    let Some(photo) = state.photo.as_ref() else {
        return;
    };
    let reference = state.reference.trim();
    if reference.is_empty() || state.note.trim().is_empty() || photo.reference != reference {
        return;
    }
    state.review = Some(ReviewSnapshot {
        reference: reference.to_owned(),
        note: state.note.trim().to_owned(),
        photo: photo.clone(),
    });
}
{"id":"fission-tabs-1","index":3,"label":"src/app/screen.rs","value":"src-app-screen-rs"}
use super::state::{capture, check_camera, prepare_review, toggle_torch, ReceivingState};
use fission::prelude::*;

fission_component! {
    pub ReceivingScreen<ReceivingState> {}
    view(_screen, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let matching_photo = state.photo.as_ref()
            .is_some_and(|photo| photo.reference == state.reference.trim());
        let can_prepare = !state.busy && !state.reference.trim().is_empty()
            && !state.note.trim().is_empty() && matching_photo;
        let image_width = (cx.view.viewport_size().width - 2.0 * tokens.spacing.l).clamp(1.0, 560.0);
    } => SafeArea(child: Scroll(child: Container(Column(gap: tokens.spacing.m, children: [
        Text(cx.tr("receiving.title")).size(tokens.typography.heading2_size),
        Text(cx.tr("receiving.explanation")),
        Row(gap: tokens.spacing.s, children: [
            Button(child: Text(cx.tr("language.english")), key: "english",
                on_press: reduce { state.locale = Locale::from("en-US"); }),
            Button(child: Text(cx.tr("language.spanish")), key: "spanish",
                on_press: reduce { state.locale = Locale::from("es-ES"); }),
        ]),
        FormControl(
            label: Some(cx.tr("receiving.reference")),
            required: true,
            child: TextInput(
                value: state.reference.clone(),
                bind(on_input): to(state.reference),
            ),
        ),
        FormControl(
            label: Some(cx.tr("receiving.note")),
            required: true,
            child: TextInput(
                value: state.note.clone(),
                bind(on_input): to(state.note),
                multiline: true,
                keyboard_type: TextInputType::Multiline,
            ),
        ),
        Button(child: Text(cx.tr("receiving.check_camera")), key: "camera-access",
            disabled: state.busy || state.torch_on,
            on_press: reduce { check_camera(state, cx); }),
        Button(child: Text(cx.tr("receiving.capture")), key: "capture",
            disabled: state.busy || state.device.is_none() || state.reference.trim().is_empty(),
            on_press: reduce { capture(state, cx); }),
        if state.device.as_ref().is_some_and(|device| device.has_flashlight) {
            Button(child: Text(cx.tr(if state.torch_on { "receiving.torch_off" } else { "receiving.torch_on" })),
                key: "torch", disabled: state.busy,
                on_press: reduce { toggle_torch(state, cx); })
        } else { Text(cx.tr("receiving.no_torch")) },
        if state.busy {
            Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr(&state.status_key)))
        },
        Text(cx.tr(&state.status_key)),
        if let Some(error) = &state.error { Code(text: error.clone()) },
        if let Some(photo) = &state.photo {
            Column(gap: tokens.spacing.s, children: [
                Text(cx.tr("receiving.photo_for").replace("{reference}", &photo.reference)),
                Image::memory(photo.bytes.clone()).size(image_width, image_width * 0.75)
                    .fit(ir_op::ImageFit::Contain).semantic_label(cx.tr("receiving.photo_label")),
            ])
        },
        Button(child: Text(cx.tr("receiving.prepare")), key: "prepare", disabled: !can_prepare,
            on_press: reduce { prepare_review(state); }),
        if let Some(review) = &state.review {
            Column(gap: tokens.spacing.s, children: [
                Text(cx.tr("receiving.prepared")).weight(tokens.typography.font_weight_semibold),
                Text(review.reference.clone()),
                Text(review.note.clone()),
                Text(cx.tr("receiving.prepared_photo").replace("{bytes}", &review.photo.bytes.len().to_string())),
            ])
        },
        Text(cx.tr("receiving.scope")).color(tokens.colors.text_secondary),
    ])).padding_all(tokens.spacing.l)))
}
{"id":"fission-tabs-1","index":4,"label":"src/i18n.rs","value":"src-i18n-rs"}
use fission::i18n::{Locale, TranslationBundle};
use fission::prelude::*;
use std::collections::HashMap;

pub fn create_env() -> Env {
    let mut env = Env::default();
    env.locale = Locale::from("en-US");
    for (locale, source) in [
        ("en-US", include_str!("../i18n/en-US.yaml")),
        ("es-ES", include_str!("../i18n/es-ES.yaml")),
    ] {
        let messages: HashMap<String, String> =
            serde_yaml::from_str(source).expect("valid voice note translations");
        env.i18n.add_bundle(TranslationBundle {
            locale: Locale::from(locale),
            messages,
        });
    }
    env
}

pub fn sync_env(state: &crate::app::ReceivingState, env: &mut Env) {
    env.locale = state.locale.clone();
}
{"id":"fission-tabs-1","index":5,"label":"src/lib.rs","value":"src-lib-rs"}
pub mod app;
mod i18n;

use app::{ReceivingScreen, ReceivingState};
use fission::prelude::*;

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
    DesktopApp::<ReceivingState, _>::new(ReceivingScreen)
        .with_env(i18n::create_env())
        .with_async(|asyncs| {
            asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
                app::jobs::collect_photo(request, cx).await
            });
        })
        .with_sync_env(i18n::sync_env)
        .run()
}

#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> {
    MobileApp::<ReceivingState, _>::new(ReceivingScreen)
        .with_env(i18n::create_env())
        .with_async(|asyncs| {
            asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
                app::jobs::collect_photo(request, cx).await
            });
        })
        .with_sync_env(i18n::sync_env)
        .run()
}

#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
    let _ = MobileApp::<ReceivingState, _>::new(ReceivingScreen)
        .with_env(i18n::create_env())
        .with_async(|asyncs| {
            asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
                app::jobs::collect_photo(request, cx).await
            });
        })
        .with_sync_env(i18n::sync_env)
        .run_with_android_app(app_handle);
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<ReceivingState, _>::new(ReceivingScreen)
        .with_env(i18n::create_env())
        .with_async(|asyncs| {
            asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
                app::jobs::collect_photo(request, cx).await
            });
        })
        .with_sync_env(i18n::sync_env)
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":6,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod i18n;

use fission::prelude::*;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
    console_error_panic_hook::set_once();
    WebApp::<app::ReceivingState, _>::new(app::ReceivingScreen)
        .with_env(i18n::create_env())
        .with_async(|asyncs| {
            asyncs.register_job(app::jobs::COLLECT_PHOTO, |request, cx| async move {
                app::jobs::collect_photo(request, cx).await
            });
        })
        .with_sync_env(i18n::sync_env)
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":7,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
receiving.title: "Photograph an arriving delivery"
receiving.explanation: "Enter the actual delivery reference and condition observed, then attach a real camera photo."
receiving.reference: "Delivery or purchase-order reference"
receiving.note: "Condition observed"
receiving.check_camera: "Check camera access and features"
receiving.capture: "Capture arrival photo"
receiving.torch_on: "Turn flashlight on"
receiving.torch_off: "Turn flashlight off"
receiving.no_torch: "Flashlight control is shown only after this camera reports a torch."
receiving.ready: "No camera request has been made."
receiving.permission_pending: "Waiting for camera permission…"
receiving.features_pending: "Checking camera features…"
receiving.denied: "Camera access was denied or restricted. Keep the note and review device policy or Settings."
receiving.unknown: "Camera permission remains unknown. The note is unchanged."
receiving.camera_ready: "The host reported a camera available. Capture still needs to succeed."
receiving.unavailable: "The camera operation is unavailable on this host."
receiving.capture_pending: "Capturing a photograph…"
receiving.image_pending: "Reading the actual image…"
receiving.attached: "The camera image is attached in this session."
receiving.failed: "The operation failed. The previous image and draft are unchanged."
receiving.unexpected: "The host returned no usable result. The previous image and draft are unchanged."
receiving.torch_pending: "Waiting for the flashlight response…"
receiving.torch_changed: "The host confirmed the flashlight request."
receiving.photo_for: "Camera photo for delivery {reference}"
receiving.photo_label: "Actual camera photo for the delivery"
receiving.prepare: "Prepare supplier review"
receiving.prepared: "Prepared review snapshot — not sent"
receiving.prepared_photo: "This snapshot contains the actual {bytes}-byte photograph."
receiving.scope: "Everything is session-local. Preparing a review does not save it or send a supplier claim. Turn the flashlight off when finished."
language.english: "English"
language.spanish: "Español"
{"id":"fission-tabs-1","index":8,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
receiving.title: "Fotografiar una entrega"
receiving.explanation: "Introduce la referencia real y el estado observado; después adjunta una foto de la cámara."
receiving.reference: "Referencia de entrega o pedido"
receiving.note: "Estado observado"
receiving.check_camera: "Comprobar acceso y funciones de cámara"
receiving.capture: "Capturar foto de llegada"
receiving.torch_on: "Encender la linterna"
receiving.torch_off: "Apagar la linterna"
receiving.no_torch: "El control aparece solo cuando esta cámara indica que tiene linterna."
receiving.ready: "No se ha solicitado acceso a la cámara."
receiving.permission_pending: "Esperando el permiso de cámara…"
receiving.features_pending: "Comprobando las funciones de cámara…"
receiving.denied: "El acceso fue denegado o restringido. Conserva la nota y revisa la política del dispositivo o Ajustes."
receiving.unknown: "El permiso sigue siendo desconocido. La nota no ha cambiado."
receiving.camera_ready: "El host indicó una cámara disponible. La captura aún debe completarse."
receiving.unavailable: "La operación de cámara no está disponible en este host."
receiving.capture_pending: "Capturando una fotografía…"
receiving.image_pending: "Leyendo la imagen real…"
receiving.attached: "La foto de cámara está adjunta durante esta sesión."
receiving.failed: "La operación falló. La imagen anterior y el borrador no han cambiado."
receiving.unexpected: "El host no devolvió un resultado utilizable. La imagen anterior y el borrador no han cambiado."
receiving.torch_pending: "Esperando la respuesta de la linterna…"
receiving.torch_changed: "El host confirmó la solicitud de linterna."
receiving.photo_for: "Foto de cámara para la entrega {reference}"
receiving.photo_label: "Foto real de cámara de la entrega"
receiving.prepare: "Preparar revisión del proveedor"
receiving.prepared: "Resumen preparado — no enviado"
receiving.prepared_photo: "Este resumen contiene la fotografía real de {bytes} bytes."
receiving.scope: "Todo permanece en esta sesión. Preparar una revisión no la guarda ni envía una reclamación. Apaga la linterna al terminar."
language.english: "Inglés"
language.spanish: "Español"
{"id":"fission-tabs-1"}
Check access first, then capture. The iOS provider takes a still photograph through AVFoundation; this example does not provide a live viewfinder or a native capture-picker screen. Do not promise that a user can frame the image through a viewfinder which the app has not implemented. Inspect the returned image and retake it when necessary.
The current iOS cancellation operation is a no-op. Therefore this screen has no pretend “Cancel capture” action. A real viewfinder, cancellation UX and lifecycle cleanup are additional product work, not implied by the capture request.
Enter a delivery reference and note, check access and capture. Confirm that the displayed image came from the active camera. Change the reference and verify that preparation stays disabled until it matches the photo, or capture a replacement for the new reference.
Show the app preview
Hide the app preview

2. Verify capture, failure and flashlight behaviour separately

The selected camera ID is used for both capture and torch requests. A flashlight button appears only when that actual camera reports a torch, and its last confirmed state changes only after SET_CAMERA_FLASHLIGHT succeeds. Permission, hardware support and a successful operation are still distinct checks.
Only one operation runs at a time, including stream consumption. A second capture cannot race a first collection job. This avoids needing a second generation-ID protocol in the small example. An app which allows several captures or navigation between receipts whilst work runs needs explicit operation identity and lifecycle policy.
Run on macOS:
fission doctor ios --project-dir .
fission devices --project-dir .
fission run --target ios --project-dir .
fission test --target ios --project-dir .
Use a signed physical iPhone build for camera and torch qualification. The simulator checks neither real sensor output nor torch illumination. The browser's provider may report no flashlight even when a phone's native provider supports one.
Test denial, a restricted device, unavailable hardware, a failed capture and a failed image read. Keep the note, previous photo and prepared snapshot available. Turn the torch off after use and verify that failure does not produce a false off/on confirmation. Check background/foreground behaviour on the phone; the boolean in this example records the last confirmed request, not continuous hardware telemetry.
Preparing the snapshot does not save a receipt or send a supplier claim. A production service must authenticate and authorize the operation, persist the actual image and report submission success only after its own completion confirms it.