The same receipt yields the full reference number locally, but loses a digit on a cloud Mac test node. Do not lower the pass criteria just yet: unless the input image, recognition language, and OS version are fixed, it is hard to pinpoint the cause. When adding OCR regression checks to iOS automated tests, start with fixed image fixtures and expected fields before discussing recognition accuracy.
1. Define a Testable Contract for Recognition Results
This workflow first uses Vision on macOS to validate a fixture, then passes the image to iOS tests. Xcode must be installed and initialized, and xcrun swift --version must run from the command line. The examples require no third-party libraries or network downloads of images.
Separate the output into three layers: raw candidate text, the normalized rectangle containing each candidate, and fields extracted by business logic. Recognizing an entire line does not mean the reference number was extracted correctly. Nor should the business layer silently replace every letter O with the digit zero.
OCR confidence is not a measure of business correctness. A high-confidence result can still misread one digit, while a low-confidence result may be entirely correct. A single threshold is not enough to decide whether a test passes.
This workflow suits regression testing for receipts, labels, and documents. It does not establish how well OCR works on camera captures: glare, poor focus, and motion blur still require real captured samples.
2. Generate a Fixed Text Image
In a separate directory, save the following as make-fixture.swift. The image uses black text on a white background, with explicit dimensions and font settings, so the test does not depend on desktop scaling or remote desktop screenshots.
import AppKit
import ImageIO
import UniformTypeIdentifiers
let width = 1200
let height = 320
let space = CGColorSpaceCreateDeviceRGB()
let context = CGContext(
data: nil,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: space,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)!
context.setFillColor(NSColor.white.cgColor)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(
cgContext: context,
flipped: false
)
("TEST 4826" as NSString).draw(
at: NSPoint(x: 90, y: 110),
withAttributes: [
.font: NSFont.monospacedSystemFont(ofSize: 96, weight: .regular),
.foregroundColor: NSColor.black
]
)
NSGraphicsContext.restoreGraphicsState()
let image = context.makeImage()!
let url = URL(fileURLWithPath: "fixture.png")
let destination = CGImageDestinationCreateWithURL(
url as CFURL,
UTType.png.identifier as CFString,
1,
nil
)!
CGImageDestinationAddImage(destination, image, nil)
guard CGImageDestinationFinalize(destination) else {
fatalError("Image encoding failed")
}
Run it once and calculate the file checksum:
set -euo pipefail
xcrun swift make-fixture.swift
shasum -a 256 fixture.png > fixture.sha256
Review the image, then commit the PNG, checksum, and expected text together. Routine regression tests should read the committed image rather than regenerate it on every run; font rendering can differ across systems and change the pixels. The generation script records the fixture's provenance. It does not guarantee a stable input.
3. Inspect Candidate Text and Normalized Bounds
Save the following as recognize.swift. It explicitly selects accurate recognition, sets English as the recognition language, and disables language correction so that dictionary-based correction does not turn reference numbers into plausible words. Adjust the language list to match your requirements, checking first which languages the current request supports.
import Foundation
import Vision
import ImageIO
let url = URL(fileURLWithPath: "fixture.png")
let request = VNRecognizeTextRequest()
request.recognitionLevel = .accurate
request.recognitionLanguages = ["en-US"]
request.usesLanguageCorrection = false
let supported = try request.supportedRecognitionLanguages()
guard supported.contains("en-US") else {
fatalError("Required recognition language unavailable")
}
let handler = VNImageRequestHandler(
url: url,
orientation: .up,
options: [:]
)
try handler.perform([request])
let rows: [[String: Any]] = (request.results ?? []).map { observation in
let box = observation.boundingBox
return [
"candidates": observation.topCandidates(3).map {
["text": $0.string, "confidence": Double($0.confidence)]
},
"bounds": [
Double(box.minX), Double(box.minY),
Double(box.width), Double(box.height)
]
]
}
let report = try JSONSerialization.data(
withJSONObject: rows,
options: [.prettyPrinted, .sortedKeys]
)
try report.write(to: URL(fileURLWithPath: "recognition.json"))
let texts = (request.results ?? []).compactMap {
$0.topCandidates(1).first?.string
}
guard texts.contains("TEST 4826") else {
fatalError("Expected text missing")
}
Run xcrun swift recognize.swift. On failure, retain recognition.json and the input image. The candidate count is an upper limit: requesting three does not guarantee that three will be returned.
Vision rectangles use a bottom-left origin, so they cannot be used directly as overlay bounds in an interface with a top-left origin. When the image is unrotated and fills its display area, flip the vertical coordinate using 1 - y - height. If scaling leaves margins, also add the offset of the actual displayed image area.
4. Reuse the Same Image in iOS Regression Tests
Add the reviewed PNG to the test resources. On the target iOS runtime, call the recognition wrapper the app actually uses rather than merely rerunning the macOS script. Record the OS version, the request's revision, the language list, and the image checksum. Before pinning a revision, confirm that the target system supports it; do not simply copy the value from another machine.
Once the basic fixture passes, add four separate sample categories:
- Blank images: the business layer should return “no usable fields,” not reuse the previous result.
- Mixed digits and letters: verify that misreadings involving
0/Oand1/Iare not handled with unconditional replacements. - Multiple reference numbers on one page: select fields by the relevant business region, not by their position in the results array.
- Rotated images: explicitly pass the correct orientation so that metadata orientation and pixel rotation are not applied twice.
Synthetic images are useful for checking integration wiring and field contracts, not for representing real-world recognition accuracy. Real samples must have sensitive information removed, and permission to use them must be retained.
5. Make Failure Reports Useful for Decisions
At a minimum, the test gate should distinguish request execution failures, missing required fields, mismatched fields, and implausible regions. Do not label every error “empty recognition result,” or configuration changes will become indistinguishable from algorithm regressions.
When comparing systems, prioritize business fields rather than requiring candidate-box floating-point values or confidence scores to match digit for digit. Region checks can verify that rectangle values are finite, that the rectangle lies within the unit range, and that its center falls inside the expected region. Derive tolerances from reviewed samples rather than copying arbitrary constants.
For every failure, archive the image checksum, configuration, candidate JSON, and expected values. Before an OS upgrade, run the fixed sample set, then review the differences manually before updating the baseline. Keeping the original evidence does far more than repeatedly lowering thresholds to explain what actually changed in a regression.
Frequently asked questions
Can a macOS Vision test replace an iOS simulator test?
No. It provides a useful fixture and result-contract preflight. Run the app’s recognition wrapper on the target iOS runtime as well, since models and supported languages can differ.
Does a high confidence score prove that a field is correct?
No. Assert the expected text and field format first. Use a representative evaluation set to calibrate any confidence threshold for additional review.
Validate your regression tests in a dedicated environment
Need an extra machine for a short release regression cycle? Rent a dedicated physical Mac mini—not a virtual machine. Teams running at full capacity year-round or only lightweight unit tests may be better off buying their own machine or using a shared environment.
Rent a dedicated Mac for testing