Build a QR code scanner into an app by using your platform's camera and barcode APIs instead of writing image decoding yourself: on iOS that means AVFoundation or the Vision framework, on Android it's ML Kit or ZXing, on cross-platform frameworks you install a maintained plugin, and in a web app you reach for getUserMedia plus a JavaScript decoder or the browser's native BarcodeDetector. The key condition is camera permission plus a real-time frame pipeline, and the scanner should default to on-device decoding so codes never leave the phone. Everything below breaks that into ordered work you can check at each stage.
QR scanning looks trivial until you ship it. Then you meet rotated codes, glare, low-contrast stickers on shipping boxes, codes that resolve to a URL and a payload you never expected, and users who deny camera access by reflex. The difference between a demo that scans a test image and a scanner people trust in a warehouse or a checkout line is mostly the boring parts: permission handling, focus and resolution choices, a debounce so one code doesn't fire five times, and validation before you act on the content. This guide walks the whole path, with the exact platform APIs, a worked performance estimate, and the failure modes that account for most bug reports.
Decide the platform and decoder before touching camera code
The first decision is not "which library" but where the decode happens. You have three families of options, and each changes the rest of your architecture.
Native platform APIs give you the best camera control, lowest latency, and no third-party dependency, but you write separate code for iOS and Android and you own the frame-handling loop. Cross-platform frameworks (React Native, Flutter, .NET MAUI) have mature scanner plugins that wrap the native engines, which usually means less code and roughly native performance, at the cost of trusting the plugin's maintenance and its permission plumbing. Web apps running in a browser are the most portable, but decoding quality depends on the browser's BarcodeDetector support or a JavaScript/WASM decoder, and you must handle HTTPS and autoplay rules.
A useful rule of thumb: if the scanner is a small feature inside an existing app, use the plugin that matches your framework and move on. If scanning is the product (a warehouse tool, a ticket validator), go native and tune the pipeline. If the scanner lives on a web page, budget extra time for browser quirks.
Separately, decide whether decoding is on-device or server-side. On-device is faster, works offline, and avoids sending camera frames anywhere, which matters for privacy and for cellular data. Server-side decoding makes sense only for odd formats or when you need to log full-resolution images for audit, and even then you should send the cropped code region, not the whole frame.
Set up permissions and the camera preview
Permission handling is where scanners lose users. Do it deliberately and early.
On iOS, add NSCameraUsageDescription to Info.plist with a sentence that explains why the camera is needed—App Review rejects vague strings, and users skip vague prompts. Request access with AVCaptureDevice.requestAccess(for: .video) before you configure a session, and check authorizationStatus on launch so returning users who denied access see a clear "open Settings" path instead of a black screen.
On Android, declare in the manifest, then request it at runtime with the Activity Result API (or the permission APIs your framework exposes). Android 6.0 and later require the runtime request; a manifest entry alone does nothing. If your app targets Android 11 and up and scans only via the camera, you don't need broad storage permissions—another reason to keep decoding on-device.
For the preview itself, the mechanics differ but the goal is the same: a live camera feed rendered into a view, with the capture session's frame stream handed to the decoder.
iOS with AVFoundation: create an AVCaptureSession, add an AVCaptureDeviceInput for the back camera, add an AVCaptureVideoDataOutput with a delegate, and attach an AVCaptureVideoPreviewLayer to a view. Set the session preset to something like .hd1280x720; higher resolutions cost CPU without improving small-code readability much, and lower ones blur dense codes. Run the session on a dedicated serial queue so the UI thread stays responsive.
Android with CameraX: bind a Preview use case to the lifecycle and a ImageAnalysis use case with a backpressure strategy of KEEP_ONLY_LATEST. That strategy is not optional—if the analyzer falls behind, KEEP_ONLY_LATEST drops stale frames instead of building a queue that makes the preview lag. Convert each ImageProxy to an InputImage and pass it to ML Kit's BarcodeScanner.
If you support both front and back cameras, expose a toggle but default to the back camera; front cameras on phones have lower resolution and worse focus for small codes.
Build the capture-to-decode pipeline and know what "success" looks like
The pipeline has four stages: capture, convert, decode, and deliver. The first two are platform plumbing; the last two are where product decisions live.
Capture. Run the video data output at a steady frame rate and let the decoder keep up. You do not need to analyze every frame; analyzing at 10–15 frames per second is usually enough for a human holding a phone, and it saves battery. On iOS, you can throttle in the delegate by timestamp; on Android, ImageAnalysis has a setTargetResolution/ResolutionSelector you can tune down.
Convert. ML Kit wants an InputImage with a rotation; AVFoundation gives you CMSampleBuffers you convert to CVPixelBuffer and feed to VNDetectBarcodesRequest (Vision) or to a CIDetector with CIDetectorTypeQRCode. Get rotation right—an unrotated buffer scans landscape codes fine and portrait codes not at all, which is a classic "works on my desk" bug.
Decode. Request only the symbologies you need. ML Kit's BarcodeScannerOptions lets you restrict formats, which speeds up detection and avoids false positives. On iOS, Vision's VNDetectBarcodesRequest accepts a symbologies list; set it to QR (and any other formats you support) rather than leaving everything on. If you use ZXing instead, it supports QR plus many 1D formats and gives you raw bytes, which matters for binary payloads.
Deliver. The decode callback typically fires several times per second while a code sits in frame. Debounce: record the last decoded string and a timestamp, and ignore repeats within roughly 1.5–2 seconds, or ignore until the scanner view is dismissed. Also stop the session or pause analysis as soon as you have a valid result, so the camera doesn't keep chewing battery behind a results screen.
Success check: point the camera at a printed QR code from arm's length in moderate light, and confirm the delegate or analyzer callback fires within about a second, with the correct payload string. If it only works up close, your resolution or focus is weak; if it fires three times for one code, your debounce is missing.
Validate and act on the payload safely
A decoded QR code is untrusted input. Treat it exactly like text typed by a stranger. This is the step most tutorials skip, and it's where real incidents happen.
First, classify the payload. QR codes can carry plain text, URLs, vCard contacts, Wi-Fi credentials, calendar events, and app-specific JSON. If your app only expects URLs, reject anything that doesn't parse as one. If you expect JSON, parse it defensively and validate a schema—never eval it, never feed it to a template that can execute, and never deserialize into types that can trigger side effects.
Second, sanitize URLs before opening them. Parse with the platform's URL parser, allow only https (and http only if you have a deliberate reason), and check the host against an allowlist when the scanner is supposed to open your own service. A QR code that points to passes a naive contains("example.com") check; parse and compare the host exactly. Showing the URL to the user with a confirmation step before navigation is the safest default for anything you didn't generate.
Third, handle binary and non-UTF-8 payloads. ZXing and some native APIs expose raw bytes; if your pipeline assumes UTF-8 strings, a code with arbitrary bytes can produce replacement characters or, worse, a garbled value that still passes a weak regex. Decode explicitly and validate the character set you expect.
Fourth, consider the payload size. QR codes can hold a few thousand bytes depending on version and error correction. If you accept large JSON payloads, enforce a length cap before parsing and a depth cap after—deeply nested JSON is a cheap denial-of-service vector.
Handle the failure modes users will actually hit
Most scanner bugs fall into a short list. Here's how to recognize and fix each.
Camera denied or unavailable. Symptom: black preview or a permission dialog that never appears. Cause: missing usage description on iOS, missing runtime request on Android, or a simulator with no camera. Fix: check authorization state on launch and render an explicit "camera access needed" screen with a button that opens app settings. Test on a physical device—simulators don't have cameras.
Preview rotated or stretched. Symptom: the image is sideways or squashed. Cause: video orientation or preview layer gravity. Fix: set the video orientation on the capture connection (iOS) or let CameraX handle rotation and confirm the ImageProxy rotation is applied to the InputImage (Android).
Scans only up close or poorly in low light. Symptom: the user has to fill the frame with the code. Cause: low capture resolution, autofocus hunting, or analysis on downscaled frames. Fix: raise resolution modestly, enable continuous autofocus, and make sure your resolution selector isn't shrinking frames below roughly 640px on the short side for dense codes.
Repeated results. Symptom: a toast or navigation fires multiple times for one code. Cause: no debounce and no pause on success. Fix: as described above—timestamp the last result, and stop analysis on success.
Works in the emulator, fails on device. Symptom: camera feed in a simulator but no scans. Cause: simulators often lack camera hardware or have degraded capture. Fix: always test on real hardware; keep a hardware test checklist in your release process.
Codes on screens or labels fail. Symptom: printed paper works, an LCD or a laminated label doesn't. Cause: glare, screen moiré, or low contrast. Fix: expose a torch toggle, and test with real materials from your actual use case—warehouse labels and event tickets are not the same as a desktop printout.
A specific stop condition: if after these fixes scanning still fails only for certain code versions or error-correction levels, the problem is probably in the decoder configuration or the image format, not in your app logic. At that point, capture a sample frame to disk in a debug build and feed it to a standalone decoder to isolate whether the bug is in capture or decode.
Cross-platform shortcuts and what they cost
If you're using React Native, Flutter, or .NET MAUI, the fastest path is a maintained plugin that wraps the native engines. On React Native, react-native-vision-camera with its code-scanner frame processor is the common choice, built on ML Kit and Vision; it's performant but version-sensitive—match the plugin version to your React Native version and follow its installation notes for iOS pods and Android Gradle settings. On Flutter, mobile_scanner wraps ML Kit on Android and Vision on iOS and handles the preview widget for you. On MAUI, BarcodeScanning.Native.Maui and similar packages wrap ZXing or platform APIs.
The trade-offs are consistent:
Less code, less control. You get the preview and callback, but tuning resolution, torch behavior, and debounce often means dropping to platform code anyway. Permission plumbing varies. Some plugins request permissions for you; others leave it to you. Read the plugin's docs rather than assuming. Version risk. Plugins lag platform SDKs. A plugin that hasn't been updated for the current Android SDK or Xcode version will cost you more time than writing the native paths would have. Binary size. ML Kit's on-device barcode model adds size; the unbundled version downloads it later, which is a poor fit for offline apps.
For web, navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } }) gets you a stream, and either BarcodeDetector (supported in several Chromium-based browsers and part of the shape-detection API family, but not universal) or a WASM decoder like ZXing-js or a similar library does the decoding. You must serve over HTTPS (or localhost), handle the user gesture requirement, and be ready for BarcodeDetector to be missing—feature-detect and fall back.
A worked performance and battery estimate
Numbers here are illustrative, not measured, but the arithmetic shows what to budget. Suppose your scanner analyzes 15 frames per second at 720p on a mid-range phone. Decoding a QR frame on-device costs roughly 5–15 milliseconds depending on the code density and whether it's a hardware-accelerated path; assume 10 ms as a working figure. At 15 frames per second, decoding consumes about 150 ms per second, or 15% of one core—enough to be noticeable if your decode runs on the main thread, which is why the analyzer queue exists.
If you analyze every frame at 30 fps instead, that doubles to roughly 30% of a core, and on a phone that also renders a preview and runs UI, you'll see dropped frames and a warm device. Throttling to 10–15 fps is the practical compromise. For a battery estimate: a phone with a 4,000 mAh battery might draw roughly 0.5–1.5 W extra during continuous camera plus decode depending on the device, so a scanning session that runs 20 minutes consumes on the order of 3–7% of the battery in rough terms. Those figures swing widely by device and screen brightness; the point is that pausing analysis when the sheet is closed and throttling the frame rate are the two levers that matter.
Latency budget: capture-to-display is typically one to three frames of pipeline delay, so at 15 fps expect roughly 60–200 ms from presenting a code to getting a callback, plus the time the user takes to aim. If your app feels slow, measure the decode call itself first—it's usually the culprit, not the camera.
Testing and shipping checklist
Test on physical devices, in the lighting and materials of your actual scenario, and with codes you generate at the versions your users will encounter. A short, concrete checklist:
Confirm the permission prompt appears once and the denied state has a recovery path. Scan a code in portrait and landscape; scan a code at an angle and partially occluded. Scan a dense code (higher QR version) and a low-contrast printed label. Confirm one decode produces exactly one action. Confirm scan stops when the view is dismissed and resumes on return. Test with the exact payload types your app accepts, including invalid ones: a malformed URL, a non-JSON string where you expect JSON, an oversized payload. Feature-detect and verify the fallback path if you're on the web. Check the app's privacy nutrition label or data-safety declaration matches your actual on-device behavior.
Ship with on-device decoding as the default, explicit payload validation, and a debounce. Those three decisions prevent nearly every incident a scanner feature generates. The camera code is the easy part; the trust boundary around the decoded string is the real engineering.