AGENT SKILL

vision-barcode-cidetector-fallback

`VNDetectBarcodesRequest` returns zero results for a perfectly valid, freshly generated QR/barcode — decode returns `nil`, not a thrown error — and OSLog shows "Could not create inference context" or similar Vision ML context failures. Reproduces reliably on the iOS Simulator (Vision's barcode ML context often can't initialize there) and can also happen on device when the ML context is unavailable or the image is low-contrast, silently dropping scannable codes. Use when a Vision-based barcode/QR decode test fails on the Simulator while the QR generator clearly works, when you're writing barcode-decode tests that must run in CI, or when you want scan robustness (competitors get dinged for "won't scan") instead of a single point of failure.

License 许可
MIT
最近更新
2026-11-07
Stars
★ 1
Forks
1

01 前言 Front Matter

name
vision-barcode-cidetector-fallback
description
`VNDetectBarcodesRequest` returns zero results for a perfectly valid, freshly generated QR/barcode — decode returns `nil`, not a thrown error — and OSLog shows "Could not create inference context" or similar Vision ML context failures. Reproduces reliably on the iOS Simulator (Vision's barcode ML context often can't initialize there) and can also happen on device when the ML context is unavailable or the image is low-contrast, silently dropping scannable codes. Use when a Vision-based barcode/QR decode test fails on the Simulator while the QR generator clearly works, when you're writing barcode-decode tests that must run in CI, or when you want scan robustness (competitors get dinged for "won't scan") instead of a single point of failure.

03 SKILL.md 正文

Vision Barcode Decode Fails on Simulator → CIDetector Fallback

Symptom

  • VNDetectBarcodesRequest returns an empty results array for a QR code in a CGImage that was just generated in the same test and is visibly valid. The decoder returns nil — it does not throw, so this looks like "no code found," not a crash.
  • OSLog/console shows something like QR Vision detect failed: Could not create inference context — Vision's barcode ML inference context failed to initialize.
  • Reproduces reliably on the iOS Simulator; the same failure mode could also surface on a real device whenever the ML context is unavailable (not reproduced on device here), silently dropping a code a human eye can read fine.
  • Any unit/UI test that generates a code then round-trips it through Vision decode fails on CI (which runs on Simulator) even though the feature works when a person tests it by hand on a phone.

Root cause

Vision's barcode detector depends on an ML inference context that the Simulator's software rendering path frequently fails to construct. This is an environment limitation, not a bug in the input image or in your request configuration — retrying the same VNDetectBarcodesRequest won't help. Treating a single detector as the whole decode pipeline means this one initialization failure (observed on Simulator; possible on device if the ML context is unavailable) silently turns into "this app can't scan codes."

Fix

Don't rely on a single detector. Try Vision first — it's fast and accurate on real hardware — then fall back to CoreImage's CIDetector QR reader, which initializes reliably on the Simulator. This is a pure upside: Vision still runs first and wins on device; CIDetector only fires when Vision comes back empty.

Scope: QR codes only. CIDetectorTypeQRCode detects QR codes and nothing else, so this fallback does not cover 1D barcodes (EAN, UPC, Code 128, ...) or other 2D symbologies (Data Matrix, PDF417, Aztec). For those there is no CIDetector equivalent; if Vision's barcode context is unavailable, options are AVCaptureMetadataOutput for live camera scanning on device (it supports those symbologies via metadataObjectTypes), or skipping the round-trip test for that symbology on Simulator.

// WRONG — single detector, silently drops codes when Vision's ML
// context fails to initialize (Simulator, or any time the ML context is unavailable)
func decode(_ image: CGImage) -> URL? {
    decodeWithVision(image)
}
// CORRECT — Vision first, CIDetector fallback
func decode(_ image: CGImage) -> URL? {
    decodeWithVision(image) ?? decodeWithCoreImage(image)
}

private func decodeWithCoreImage(_ image: CGImage) -> URL? {
    let ciImage = CIImage(cgImage: image)
    guard let detector = CIDetector(
        ofType: CIDetectorTypeQRCode,
        context: nil,
        options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]
    ) else { return nil }

    for case let qr as CIQRCodeFeature in detector.features(in: ciImage) {
        if let message = qr.messageString, let url = URL(string: message) {
            return url
        }
    }
    return nil
}

Keep decodeWithVision and decodeWithCoreImage as pure, nonisolated functions over a CGImage — no actor hops, no UI — so both the Vision callback path and CI test code can call the combined decode(_:) directly. Log which path answered (Vision vs. CIDetector) at debug level so a Simulator-only failure pattern is visible in test output instead of looking like a flaky decode.

Evidence

  • Found writing barcode-decode tests for a scanning app's QR/NFC tag flow: a test that generates a QR then feeds it straight back into VNDetectBarcodesRequest failed only on the iOS 26 Simulator, with OSLog showing Could not create inference context. Adding the CIDetector fallback made the same test pass on Simulator and left on-device behavior unchanged (Vision still answers first there).

Related skills

  • scan-capture-quality-gates — a different failure stage: that skill covers whether the captured frame itself is good enough to decode (blur, auto-naming from OCR prose); this skill covers the decoder failing on an otherwise-good frame. A soft blur gate reduces how often you even need this fallback to fire.
  • vision-layout-ocr-grounding — a sibling Vision-pipeline concern, but about text layout/reading order for on-device AI grounding, not barcode detection; both are examples of "don't trust one Vision output path," applied to different Vision request types.
  • swift6-mainactor-compile-fixes — keep decodeWithVision/decodeWithCoreImage nonisolated pure compute per that playbook, so the fallback chain can run off-main from capture-delivery callbacks.

04 同仓库更多 Skills

abhijitbansal
abhijitbansal/claude-skills

second-wind

Orchestrate long unattended Claude Code runs across multiple repos with the wind CLI. Use when the user wants to run Claude Code overnight, resume sessions after the 5-hour usage limit, run Claude in many repos at once via tmux, or says "set up second wind", "wind up", "overnight run", "resume after limit", "usage limit orchestrator".

★ 1
abhijitbansal
abhijitbansal/claude-skills

structured-output-adaptive-thinking-token-bloat

A Claude API call using output_config.format (json_schema structured outputs) with thinking:{type:"adaptive"} burns most of its output budget on thinking (observed ~21k of ~24k tokens) without improving JSON quality, making the run up to ~5x more expensive than the same call with thinking omitted — use when calling the Messages API with a json_schema output format for extraction, ranking, classification, or summarization tasks, or when a schema-constrained call's usage.output_tokens is far larger than the returned JSON.

★ 1
abhijitbansal
abhijitbansal/claude-skills

review

Apply a code-review lens to a diff, branch, or file — find correctness bugs, security issues, and quality problems, ranked by severity, with a concrete fix for each. Use when the user says "review this", "review my diff", "check this PR", "look this over before I commit", or "is this safe". Skip when the user wants the code written, not reviewed.

★ 1
abhijitbansal
abhijitbansal/claude-skills

refresh

Rebuild the prompt-craft command registry and usage profile, and print a summary of installed commands and your personalized recommendations. Use when you install or update plugins and want the advisor to pick them up immediately, or say "refresh prompt-craft", "rebuild the command registry".

★ 1
abhijitbansal
abhijitbansal/claude-skills

refactor

Apply a refactoring lens — restructure code without changing behavior, guarded by tests that pass before and after. Use when the user says "refactor", "clean this up", "extract this", "simplify this", "reduce duplication", or "make this readable" on existing working code. Skip when the change is meant to alter behavior (that's a feature or a fix).

★ 1
abhijitbansal
abhijitbansal/claude-skills

plan

Decompose a non-trivial task into an explicit, tracked plan with goals and per-step acceptance criteria before writing code. Use when the user says "plan this", "break this down", "what's the plan", or asks for a multi-step feature/refactor that touches more than one file. Pairs with plan mode. Skip for single-edit changes that need no decomposition.

★ 1