OCR in Swift: which Apple API to use
macOS 26 and up: RecognizeDocumentsRequest. Older:
VNRecognizeTextRequest. Nothing to install.
98.9%
of words found by RecognizeDocumentsRequest
No Mac? OCR Actor, $0.006 a scanned page
Tesseract, not Apple Vision, on Apify's servers: files leave your computer.
The code, with a fallback for older Macs
ocr.swift prints the text of an image, with top-level await:
import Foundation
import Vision
let url = URL(fileURLWithPath: CommandLine.arguments[1])
if #available(macOS 26, *) {
let documents = try await RecognizeDocumentsRequest().perform(on: url)
print(documents.map(\.document.text.transcript).joined(separator: "\n"))
} else {
let request = VNRecognizeTextRequest()
request.recognitionLevel = .accurate
try VNImageRequestHandler(url: url).perform([request])
let lines = request.results?.compactMap { $0.topCandidates(1).first?.string } ?? []
print(lines.joined(separator: "\n"))
}
On this Mac it printed the same text as docs.swift below, byte for byte, on all 10 pages.
Build it with swiftc, no Xcode project
swiftc -O ocr.swift -o ocr
./ocr page.jpg
It also builds in Swift 6 mode, and for macOS 10.15, with no warnings. Forced on this Mac, the fallback gave the same text as vn.swift.
Want @main with an async main()? In a
one-file build, swiftc stops:
error: 'main' attribute cannot be used in a module that contains top-level code
Add -parse-as-library to the swiftc line, or
drop @main and use top-level await, as above.
docs.swift: text, paragraphs and tables, 32 lines
// Text, paragraphs and tables with RecognizeDocumentsRequest (Vision, macOS 26+, iOS 26+).
// Build: swiftc -O docs.swift -o docs Run: ./docs <out dir> <image>...
// Writes <name>.txt (the transcript) and <name>.json (paragraphs, tables as rows of cell text), prints name<TAB>seconds.
import Foundation
import Vision
let args = CommandLine.arguments
let outDir = URL(fileURLWithPath: args[1])
let request = RecognizeDocumentsRequest()
for path in args.dropFirst(2) {
let url = URL(fileURLWithPath: path)
let start = Date()
let documents = try await request.perform(on: url)
let seconds = Date().timeIntervalSince(start)
var text: [String] = [], paragraphs: [String] = [], lines = 0, tables: [[[String]]] = []
for document in documents.map(\.document) {
text.append(document.text.transcript)
lines += document.text.lines.count
paragraphs += document.paragraphs.map(\.transcript)
tables += document.tables.map { table in
table.rows.map { row in row.map { $0.content.text.transcript } }
}
}
let name = url.deletingPathExtension().lastPathComponent
try text.joined(separator: "\n").write(
to: outDir.appendingPathComponent(name + ".txt"), atomically: true, encoding: .utf8)
let info: [String: Any] = [
"documents": documents.count, "lines": lines, "paragraphs": paragraphs, "tables": tables,
]
try JSONSerialization.data(withJSONObject: info).write(to: outDir.appendingPathComponent(name + ".json"))
print("\(name)\t\(seconds)")
}
vn.swift: VNRecognizeTextRequest only, 22 lines
// OCR with VNRecognizeTextRequest, the classic Vision API (macOS 10.15+, iOS 13+).
// Build: swiftc -O vn.swift -o vn Run: ./vn accurate|fast <out dir> <image>...
// Writes <out dir>/<name>.txt (one line per observation) and prints name<TAB>seconds.
import Foundation
import Vision
let args = CommandLine.arguments
let outDir = URL(fileURLWithPath: args[2])
for path in args.dropFirst(3) {
let url = URL(fileURLWithPath: path)
let start = Date()
let request = VNRecognizeTextRequest()
request.recognitionLevel = args[1] == "fast" ? .fast : .accurate
request.usesLanguageCorrection = true
try VNImageRequestHandler(url: url).perform([request])
let lines = (request.results ?? []).compactMap { $0.topCandidates(1).first?.string }
let seconds = Date().timeIntervalSince(start)
let name = url.deletingPathExtension().lastPathComponent
try lines.joined(separator: "\n").write(
to: outDir.appendingPathComponent(name + ".txt"), atomically: true, encoding: .utf8)
print("\(name)\t\(seconds)")
}
Close on words, far apart on speed
| API, macOS | Found | Seconds a page |
|---|---|---|
RecognizeDocuments, 26
|
1,934 | 0.77 to 0.97 |
VNRecognizeText, 10.15
|
1,932 | 0.87 to 0.95 |
RecognizeText, 15
|
1,931 | 1.11 to 1.21 |
Live Text, ImageAnalyzer, 13 |
1,929 | 0.244 to 0.249 |
VNRecognizeText .fast
|
1,628 | 0.23 |
| Tesseract 5.5.4, earlier run | 1,877 | 2.27 |
| Our Actor's code, earlier run | 1,880 | 5.4 |
- The four APIs each gave the same text in all 3 runs.
- Live Text's OCR runs in mediaanalysisd, a system daemon, at its own priority. Ours ran at background priority, so part of its lead may be priority.
Only the macOS 26 API reads table cells
54 of 65 cells exact on a blurry invoice scan
13 x 5 rows and columns, the true shape
The misses: 4 empty cells, single digits in a narrow column, and 7 misread cells.
Read cells as document.tables, then
table.rows, then
cell.content.text.transcript, as docs.swift does.
The other APIs return lines, not cells. VNRecognizeTextRequest and RecognizeTextRequest went column by column, so the rows were lost. Live Text went row by row.
Two columns in order, on an easy page
Our own two-column sample has a wide gutter, an easy case. Every
accurate API read the columns in order. .fast mixed them:
142 of 227 words in order.
Apple Vision OCR vs Tesseract, in Python on many languages, found Vision skipping vertical Chinese, Japanese and Korean columns. That is a harder layout, not tested here.
Chinese came out garbled by default
One line each, no language set. German and Ukrainian came out exact in
all four APIs. Chinese did not, in
VNRecognizeTextRequest and
RecognizeTextRequest:
ЭŁÆŒíRł7, ‡łì]ƼЙ##•
Both default to English, with language detection off. Set
recognitionLanguages or
automaticallyDetectsLanguage = true, and both read it
exactly. RecognizeDocumentsRequest and Live Text read it as is.
With only zh-Hans set, German and Ukrainian came out in Latin look-alikes. List every language you expect.
Five gotchas in Apple's text APIs
-
Names differ. RecognizeTextRequest has
usesLanguageCorrectionandautomaticallyDetectsLanguage. RecognizeDocumentsRequest hasuseLanguageCorrectionandautomaticallyDetectLanguage, intextRecognitionOptions. -
No fast mode. RecognizeDocumentsRequest has no
recognitionLevel. -
en_US, not en-US. VNRecognizeTextRequest's default
recognitionLanguagesis["en_US"], but its supported list saysen-US. -
Old targets fail. Built for macOS 15, docs.swift
stops:
'RecognizeDocumentsRequest' is only available in macOS 26.0 or newer. Wrap the call inif #available, as ocr.swift does. -
A missing file gives a misleading error, such as a
zero-dimensioned image. Check
FileManager.default.fileExists(atPath:)first.
The missing-file errors, as printed
VNRecognizeTextRequest:
Swift/ErrorType.swift:254: Fatal error: Error raised at top level: Error Domain=com.apple.Vision Code=13 "CRImage Reader Detector was given zero-dimensioned image (0 x 0)" UserInfo={NSLocalizedDescription=CRImage Reader Detector was given zero-dimensioned image (0 x 0)}
RecognizeTextRequest and RecognizeDocumentsRequest:
Swift/ErrorType.swift:254: Fatal error: Error raised at top level: Vision.VisionError.outOfBoundsError("Vision.VisionError.invalidImage(\"Zero-dimensioned image (0.0 x 0.0\")")
Live Text:
Swift/ErrorType.swift:254: Fatal error: Error raised at top level: Error Domain=NSOSStatusErrorDomain Code=-50 "paramErr: error in user parameter list" UserInfo={NSLocalizedDescription=[MADServicePublic] Failed to consume sandbox extension}
What I did not test
- iOS, Intel Macs, and macOS before 26.6. The macOS floors come from the SDK and compile errors. Before macOS 12, the tool also needs Swift's concurrency library next to it.
- Japanese, Korean, handwriting, phone photos, rotated pages and foreground priority.
- Hard two-column pages, and more than one table.
- Lists, barcodes and merged cells in RecognizeDocumentsRequest.
How I tested it
- 10 scanned book pages, 1,955 true words, 1920-pixel JPEGs: the pages of my JPG to text test.
- Apple M5 Max, macOS 26.6, Xcode 27.2, Swift 6.4.2.
- Each API ran as a small Swift tool built with swiftc -O: 3 runs each, .fast once, one at a time, at background priority.
- Seconds a page are timed inside the process, warm: pages 2 to 10, since page 1 loads the model. A range is the lowest and highest mean of 3 runs.
- Score: true words found in order.
- Table: a 13 x 5 invoice scan. Columns: a made-up newsletter page from our sample scans.
- Tesseract and Actor rows: earlier runs on the same 10 pages, not rerun. Their seconds are the whole run for each image, so they are not like for like.
- Vision and VisionKit ship with macOS. They are not open source; Apple's SDK terms apply.
- Scripts and results stay in our private repo, in research/bench/swift-ocr-2026-11-24/.
Questions people ask
Which macOS does RecognizeDocumentsRequest need?
macOS 26 or later, or iOS 26. On older systems, use VNRecognizeTextRequest: it goes back to macOS 10.15.
Is RecognizeTextRequest better than VNRecognizeTextRequest?
Not on these pages. It is the newer async Swift API, but it was slower here. Both report revision 3, yet their text matched on only 1 page of 10.
Do Vision and Live Text need an app or a run loop?
No. All four ran from plain command line tools with top-level code: no run loop, no NSApplication, no main actor code.
Which languages does Apple's OCR read?
30 language codes at the accurate level, the same list in all four APIs. Norwegian alone has 3. The fast level reads 6 codes. Vietnamese is listed as vi-VT.
Need only the text?
No Mac, or a Linux server? Our Actor turns scanned PDFs and images into Markdown. It runs Tesseract, not Apple Vision, and Apple's APIs beat it on these pages.
Or send us the scan. Tack, our AI, does the job for $29, up to 50 pages. First page free.