Scan barcodes on iOS with Rust

Receive a user-entered purchase order through real barcode results or manual SKU entry, without over-receiving an expected line.
iOS

What you will build

Apply one receiving rule to scanner and manual input: match an expected SKU and add one unit only whilst capacity remains.
Create and lock the actual expected order before receiving starts
Reject unknown labels and full lines without changing their counts
Distinguish the iOS still-photo decoder and current cancellation limits from a live scanner
A barcode supplies an identifier, not permission to change stock. When receiving a supplier delivery, the decoded SKU still needs to match an expected order line, and that line must still have capacity for another unit.
We will build that reconciliation rule and use it from both a real camera scan and manual entry. Start by entering the expected order from your paperwork, then lock it for receiving. This gives the native app a complete useful workflow rather than an empty screen which only works when a browser launcher injects a sample purchase order.

Create the shared iOS app

Complete iOS setup if needed.
cargo install cargo-fission
fission init greenway-receiving-ios
cd greenway-receiving-ios
fission add-target ios --project-dir .
fission add-capability barcode-scanner --project-dir .
cargo add serde_yaml
Review NSCameraUsageDescription in the generated iOS host. The capability command adds the camera configuration; its explanation should accurately describe reading delivery labels.
Keep the generated src/main.rs. The normal native and Web launchers below run the same empty, user-configured receiving app and the real provider available to that target. There is no fixture-only order or hidden browser-only success path.

Run the finished example

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

1. Make the receiving rule the authority for both input paths

The order is application state. Its expected quantities can be entered before receiving starts but cannot be edited during the receiving session. Each line has one normalized SKU, so the same printed label cannot accidentally select two different lines.
record_sku performs the shared transition: find the expected line, reject unknown or full lines, then add exactly one unit. A scan failure never calls that transition. Counts are derived from the records rather than maintained as a second mutable total.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/app/state.rs","value":"src-app-state-rs"},{"index":2,"label":"src/app/setup.rs","value":"src-app-setup-rs"},{"index":3,"label":"src/app/line.rs","value":"src-app-line-rs"},{"index":4,"label":"src/app/screen.rs","value":"src-app-screen-rs"},{"index":5,"label":"src/i18n.rs","value":"src-i18n-rs"},{"index":6,"label":"src/lib.rs","value":"src-lib-rs"},{"index":7,"label":"preview/lib.rs","value":"preview-lib-rs"},{"index":8,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"},{"index":9,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
mod line;
mod screen;
mod setup;
pub mod state;
pub use screen::ReceivingScreen;
pub use state::ReceivingState;
{"id":"fission-tabs-1","index":1,"label":"src/app/state.rs","value":"src-app-state-rs"}
use fission::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OrderLine {
    pub sku: String,
    pub product: String,
    pub expected: u32,
    pub received: u32,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReceivingState {
    pub locale: Locale,
    pub reference: String,
    pub lines: Vec<OrderLine>,
    pub started: bool,
    pub scanner_busy: bool,
    pub status_key: String,
    pub status_sku: String,
    pub diagnostic: Option<String>,
}

impl Default for ReceivingState {
    fn default() -> Self {
        Self {
            locale: Locale::from("en-US"),
            reference: String::new(),
            lines: Vec::new(),
            started: false,
            scanner_busy: false,
            status_key: "receiving.ready".into(),
            status_sku: String::new(),
            diagnostic: None,
        }
    }
}
impl GlobalState for ReceivingState {}

pub fn expected_units(value: &str) -> Option<u32> {
    let value = value.trim();
    if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    value
        .parse::<u32>()
        .ok()
        .filter(|value| (1..=100_000).contains(value))
}

pub fn add_line(state: &mut ReceivingState, sku: &str, product: &str, units: &str) -> bool {
    if state.started {
        return false;
    }
    let sku = sku.trim().to_ascii_uppercase();
    let Some(expected) = expected_units(units) else {
        return false;
    };
    if sku.is_empty() || product.trim().is_empty() || state.lines.iter().any(|line| line.sku == sku)
    {
        return false;
    }
    state.lines.push(OrderLine {
        sku,
        product: product.trim().into(),
        expected,
        received: 0,
    });
    true
}

pub fn record_sku(state: &mut ReceivingState, value: &str) -> bool {
    let sku = value.trim().to_ascii_uppercase();
    state.status_sku = sku.clone();
    state.diagnostic = None;
    if !state.started {
        state.status_key = "receiving.start_first".into();
        return false;
    }
    let Some(line) = state.lines.iter_mut().find(|line| line.sku == sku) else {
        state.status_key = "receiving.unknown".into();
        return false;
    };
    if line.received >= line.expected {
        state.status_key = "receiving.full".into();
        return false;
    }
    line.received += 1;
    state.status_key = "receiving.recorded".into();
    true
}

pub fn scan(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    if state.scanner_busy || !state.started {
        return;
    }
    state.scanner_busy = true;
    state.status_key = "receiving.scanning".into();
    state.diagnostic = None;
    let ok = cx.effects.bind(Scanned, reduce_with!(scanned));
    let err = cx.effects.bind(ScanFailed, reduce_with!(scan_failed));
    cx.effects
        .barcode_scanner()
        .scan(BarcodeScanRequest {
            formats: vec![BarcodeFormat::Code128, BarcodeFormat::QrCode],
            prompt: None,
            camera_id: None,
            timeout_ms: Some(20_000),
            allow_multiple: false,
        })
        .on_ok(ok)
        .on_err(err);
}

#[fission_reducer(Scanned)]
fn scanned(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    state.scanner_busy = false;
    let Some(results) = cx.input.capability_ok(SCAN_BARCODE) else {
        state.status_key = "receiving.unexpected".into();
        return;
    };
    let Some(label) = results.items.first() else {
        state.status_key = "receiving.no_label".into();
        return;
    };
    record_sku(state, &label.value);
}

#[fission_reducer(ScanFailed)]
fn scan_failed(state: &mut ReceivingState, cx: &mut ReducerContext<ReceivingState>) {
    state.scanner_busy = false;
    let error = cx.input.capability_error(SCAN_BARCODE);
    state.status_key = match error.as_ref().map(|error| error.code.as_str()) {
        Some("cancelled" | "canceled") => "receiving.cancelled",
        Some("permission_denied") => "receiving.denied",
        Some("unsupported") => "receiving.unsupported",
        Some("timeout") => "receiving.timeout",
        Some("camera_error") => "receiving.camera_error",
        _ => "receiving.failed",
    }
    .into();
    state.diagnostic = error
        .map(|error| format!("{}: {}", error.code, error.message))
        .or_else(|| {
            cx.input
                .capability_error_message(SCAN_BARCODE)
                .map(str::to_owned)
        });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn receiving_never_exceeds_or_changes_an_unknown_line() {
        let mut state = ReceivingState::default();
        assert!(add_line(&mut state, "A-1", "First product", "1"));
        assert!(add_line(&mut state, "B-2", "Second product", "2"));
        state.started = true;
        assert!(record_sku(&mut state, "a-1"));
        let first = state.lines.clone();
        assert!(!record_sku(&mut state, "A-1"));
        assert!(!record_sku(&mut state, "UNKNOWN"));
        assert_eq!(state.lines, first);
        assert!(record_sku(&mut state, "B-2"));
        assert_eq!(state.lines[0].received, 1);
        assert_eq!(state.lines[1].received, 1);
    }

    #[test]
    fn order_setup_rejects_duplicate_sku_and_invalid_units() {
        let mut state = ReceivingState::default();
        assert!(add_line(&mut state, "A-1", "Product", "2"));
        assert!(!add_line(&mut state, "a-1", "Duplicate", "3"));
        assert_eq!(expected_units("2.5"), None);
        assert_eq!(expected_units("0"), None);
        assert_eq!(expected_units("100001"), None);
    }
}
{"id":"fission-tabs-1","index":2,"label":"src/app/setup.rs","value":"src-app-setup-rs"}
use super::state::{add_line, ReceivingState};
use fission::prelude::*;

fission_component! {
    pub OrderSetup<ReceivingState> {
        state {
            sku: String = String::new(),
            product: String = String::new(),
            units: String = String::new(),
            invalid: bool = false,
        }
    }
    view(form, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
    } => Column(gap: tokens.spacing.s, children: [
        TextInput(
            value: state.reference.clone(), bind(on_input): to(state.reference),
            label: Some(TextContent::Key("receiving.reference".into())),
        ),
        TextInput(
            value: form.sku.clone(), bind(on_input): to(form.sku),
            label: Some(TextContent::Key("receiving.sku".into())),
        ),
        TextInput(
            value: form.product.clone(), bind(on_input): to(form.product),
            label: Some(TextContent::Key("receiving.product".into())),
        ),
        TextInput(
            value: form.units.clone(), bind(on_input): to(form.units),
            label: Some(TextContent::Key("receiving.units".into())),
            helper_text: Some(TextContent::Key("receiving.units_help".into())),
            keyboard_type: TextInputType::Number, autocorrect: false,
        ),
        Button(
            child: Text(cx.tr("receiving.add_line")), key: "add-order-line",
            on_press: reduce {
                form.invalid = !add_line(state, &form.sku, &form.product, &form.units);
                if !form.invalid {
                    form.sku.clear(); form.product.clear(); form.units.clear();
                }
            },
        ),
        if form.invalid { Text(cx.tr("receiving.invalid_setup")) },
        Button(
            child: Text(cx.tr("receiving.start")), key: "start-receiving",
            disabled: state.reference.trim().is_empty() || state.lines.is_empty(),
            on_press: reduce {
                if !state.reference.trim().is_empty() && !state.lines.is_empty() {
                    state.started = true;
                }
            },
        ),
    ])
}
{"id":"fission-tabs-1","index":3,"label":"src/app/line.rs","value":"src-app-line-rs"}
use super::state::ReceivingState;
use fission::prelude::*;

fission_component! {
    pub OrderLineRow<ReceivingState> {
        props { sku: String }
    }
    view(row, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let line = state.lines.iter().find(|line| line.sku == row.sku);
    } => if let Some(line) = line {
        Container(Column(gap: tokens.spacing.s, children: [
            Text(line.product.clone()).weight(tokens.typography.font_weight_semibold),
            Text(line.sku.clone()),
            Text(cx.tr("receiving.line_count")
                .replace("{received}", &line.received.to_string())
                .replace("{expected}", &line.expected.to_string())),
        ]))
        .padding_all(tokens.spacing.m)
        .border(tokens.colors.border, 1.0)
        .border_radius(tokens.radii.medium)
    } else {
        Spacer()
    }
}
{"id":"fission-tabs-1","index":4,"label":"src/app/screen.rs","value":"src-app-screen-rs"}
use super::{
    line::OrderLineRow,
    setup::OrderSetup,
    state::{record_sku, scan, ReceivingState},
};
use fission::prelude::*;

fission_component! {
    pub ReceivingScreen<ReceivingState> {
        state { manual_sku: String = String::new() }
    }
    view(screen, state, cx) {
        let tokens = &cx.view.env().theme.tokens;
        let received: u64 = state.lines.iter().map(|line| u64::from(line.received)).sum();
        let expected: u64 = state.lines.iter().map(|line| u64::from(line.expected)).sum();
    } => SafeArea(
        child: Scroll(
            child: Container(Column(gap: tokens.spacing.m, children: [
                Text(cx.tr("receiving.heading")).size(tokens.typography.heading2_size),
                Text(cx.tr("receiving.session")),
                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"); },
                    ),
                ]),
                if !state.started {
                    OrderSetup
                } else {
                    Column(gap: tokens.spacing.s, children: [
                        Text(state.reference.clone()),
                        Button(
                            child: Text(cx.tr("receiving.scan")), key: "scan-label",
                            disabled: state.scanner_busy,
                            on_press: reduce { scan(state, cx); },
                        ),
                        TextInput(
                            value: screen.manual_sku.clone(), bind(on_input): to(screen.manual_sku),
                            label: Some(TextContent::Key("receiving.manual".into())),
                            read_only: state.scanner_busy,
                        ),
                        Button(
                            child: Text(cx.tr("receiving.record")), key: "record-unit",
                            disabled: state.scanner_busy || screen.manual_sku.trim().is_empty(),
                            on_press: reduce {
                                if !state.scanner_busy && record_sku(state, &screen.manual_sku) {
                                    screen.manual_sku.clear();
                                }
                            },
                        ),
                    ])
                },
                Text(cx.tr("receiving.total")
                    .replace("{received}", &received.to_string())
                    .replace("{expected}", &expected.to_string())),
                for line in &state.lines {
                    OrderLineRow(line.sku.clone(), key: line.sku.clone())
                },
                if state.scanner_busy {
                    Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr("receiving.scanning")))
                },
                Text(cx.tr(&state.status_key).replace("{sku}", &state.status_sku)),
                if let Some(error) = &state.diagnostic { Code(text: error.clone()) },
            ]))
            .padding_all(tokens.spacing.l),
        ),
    )
}
{"id":"fission-tabs-1","index":5,"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 receiving 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":6,"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_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_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_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_sync_env(i18n::sync_env)
        .run()
        .map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":7,"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_sync_env(i18n::sync_env)
        .mount("#fission-web-mount")
        .run()
        .map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":8,"label":"i18n/en-US.yaml","value":"i18n-en-us-yaml"}
receiving.heading: "Receive a supplier delivery"
receiving.session: "Enter the expected order from your paperwork, then start receiving. Records stay in memory; no supplier service or stock database is connected."
receiving.reference: "Purchase-order reference"
receiving.sku: "Expected product SKU"
receiving.product: "Product name"
receiving.units: "Expected whole units"
receiving.units_help: "Use a whole quantity from 1 to 100000."
receiving.add_line: "Add expected order line"
receiving.invalid_setup: "Enter a unique SKU, a product name and a valid whole quantity."
receiving.start: "Lock the order and start receiving"
receiving.line_count: "{received} of {expected} units received"
receiving.total: "Total: {received} of {expected} units"
receiving.manual: "SKU printed on the delivered product"
receiving.record: "Record one delivered unit"
receiving.scan: "Photograph and read one QR or Code 128 label"
receiving.ready: "Set up the expected order before receiving."
receiving.start_first: "Start receiving before counting a product."
receiving.recorded: "Recorded one unit of {sku}."
receiving.unknown: "{sku} is not on this order. No quantity changed."
receiving.full: "{sku} has reached its expected quantity. No extra unit was counted."
receiving.scanning: "Waiting for the camera and barcode result…"
receiving.unexpected: "The scanner returned no usable result. Quantities are unchanged."
receiving.no_label: "No supported label was decoded. Try another photograph or enter the SKU."
receiving.cancelled: "Scanning was cancelled. Quantities are unchanged."
receiving.denied: "Camera access was denied. Review Settings or enter the SKU manually."
receiving.unsupported: "This host cannot scan a barcode. Enter the printed SKU manually."
receiving.timeout: "The scanner reported a timeout. Retry or enter the SKU."
receiving.camera_error: "The iOS camera operation did not complete. Quantities are unchanged; retry or enter the SKU."
receiving.failed: "Scanning failed. Quantities are unchanged; retry or enter the SKU."
language.english: "English"
language.spanish: "Español"
{"id":"fission-tabs-1","index":9,"label":"i18n/es-ES.yaml","value":"i18n-es-es-yaml"}
receiving.heading: "Recibir una entrega del proveedor"
receiving.session: "Introduce el pedido de tus documentos y comienza la recepción. Los registros están en memoria; no hay un servicio del proveedor ni una base de existencias conectados."
receiving.reference: "Referencia del pedido"
receiving.sku: "SKU del producto esperado"
receiving.product: "Nombre del producto"
receiving.units: "Unidades enteras esperadas"
receiving.units_help: "Usa una cantidad entera entre 1 y 100000."
receiving.add_line: "Añadir línea esperada al pedido"
receiving.invalid_setup: "Introduce un SKU único, un nombre de producto y una cantidad entera válida."
receiving.start: "Bloquear el pedido y comenzar la recepción"
receiving.line_count: "{received} de {expected} unidades recibidas"
receiving.total: "Total: {received} de {expected} unidades"
receiving.manual: "SKU impreso en el producto entregado"
receiving.record: "Registrar una unidad entregada"
receiving.scan: "Fotografiar y leer una etiqueta QR o Code 128"
receiving.ready: "Configura el pedido antes de recibir productos."
receiving.start_first: "Comienza la recepción antes de contar un producto."
receiving.recorded: "Registrada una unidad de {sku}."
receiving.unknown: "{sku} no está en este pedido. Ninguna cantidad cambió."
receiving.full: "{sku} ya alcanzó la cantidad esperada. No se contó otra unidad."
receiving.scanning: "Esperando la cámara y el resultado del código…"
receiving.unexpected: "El escáner no devolvió un resultado utilizable. Las cantidades no cambian."
receiving.no_label: "No se pudo leer una etiqueta compatible. Prueba otra foto o escribe el SKU."
receiving.cancelled: "Se canceló el escaneo. Las cantidades no cambian."
receiving.denied: "Se denegó el acceso a la cámara. Revisa Ajustes o escribe el SKU."
receiving.unsupported: "Este host no puede leer códigos. Introduce el SKU impreso."
receiving.timeout: "El escáner indicó un tiempo de espera agotado. Reintenta o escribe el SKU."
receiving.camera_error: "La operación de cámara de iOS no terminó. Las cantidades no cambian; reintenta o escribe el SKU."
receiving.failed: "El escaneo ha fallado. Las cantidades no cambian; reintenta o escribe el SKU."
language.english: "Inglés"
language.spanish: "Español"
{"id":"fission-tabs-1"}
Enter an order reference and two product lines with quantities one and two. Start receiving, manually record the first product and try it again: its count must stay at one. Enter an unknown SKU and confirm that neither line changes. The order's expected quantities must no longer be editable.
Show the app preview
Hide the app preview

2. Exercise the actual camera provider and its limits

The current iOS scanner opens a camera photograph flow and decodes the returned image. It is not a continuously running viewfinder which automatically recognizes a label as it enters the frame. The button describes photographing and reading a label so its wording matches that mechanism.
The provider wraps camera failures as camera_error, including cases for which the underlying camera had more specific cancellation or permission information. The screen therefore preserves counts and offers manual entry without guessing which event occurred from an error-message string. Other providers may return the specific codes handled above. The current iOS implementation also does not enforce the requested scanner timeout or implement immediate scan cancellation; do not promise those behaviors merely because the request type has a timeout field.
cargo test
fission doctor ios --project-dir .
fission devices --project-dir .
fission run --target ios --project-dir .
fission test --target ios --project-dir .
Select a simulator with the simulator guide, then follow the iPhone installation guide for camera qualification on hardware. Enter your expected lines on that device, photograph a matching QR or Code 128 label and verify that only its line increases.
Cancel the camera, deny access in a fresh permission context, photograph an unreadable label and try a SKU outside the order. In every case, check the actual returned state and ensure counts remain intact. Do not require a cancellation-specific message from a provider which currently erases that distinction. Test the manual path afterwards, including full-line rejection.
The included tests cover quantity bounds and unknown identifiers, not the camera. Check long product names, both languages, larger text and the keyboard on the rendered target. This session has no stock backend or persistence; production receiving would need its own authorized, durable commit rather than treating an in-memory counter as a warehouse update.