You build a QR code generator in Swift by feeding a string to Core Image's CIQRCodeGenerator filter, scaling the resulting bitmap with a non-interpolated transform, and rendering it through a UIImage or SwiftUI Image. The whole job takes roughly 30 lines of production code because Apple ships the encoder in the Core Image framework starting with iOS 7. The key condition is that the input must be UTF-8 encoded data, and the output is a small, blocky image that must be scaled with nearest-neighbor sampling to stay scannable. Everything beyond that—error correction, color, logo overlays, export—is refinement on the same foundation. This guide walks through the variable class, the renderer, a SwiftUI wrapper, and the failure cases that produce QR codes scanners can't read.

Where QR generation actually happens in the Apple stack

Apple does not expose a dedicated QR encoder class. Instead, Core Image registers CIQRCodeGenerator as a built-in filter with the identifier "CIQRCodeGenerator". You construct it through CIFilter(name:) or, more safely on modern SDKs, through the typed CIFilter.qrCodeGenerator() convenience. The filter takes exactly two inputs: a Data object under the key "inputMessage" and a String under "inputCorrectionLevel". It outputs a CIImage whose extent is a small number of pixels per module—typically 21×21 modules for the smallest version, growing as payload size increases.

The reason this matters is architectural. Because the filter lives in Core Image, the same code path works on iOS, iPadOS, macOS, watchOS, and tvOS with no platform branching. You do not need a third-party dependency, and you get Apple's implementation of the QR specification, which follows ISO/IEC 18004. The trade-off is limited control: Core Image's filter does not let you set the QR version directly, choose mask patterns, or embed structured-append data. The encoder picks the smallest version that fits your payload at the correction level you specify, and it decides the mask automatically. For the overwhelming majority of generator use cases—URLs, contact cards, Wi-Fi credentials, plain text—that automatic behavior is exactly what you want.

One historical wrinkle: very old Core Image documentation listed the correction level input as optional, and some sample code omitted it. In practice the filter expects the key to be present; omitting it can produce a nil output on some OS versions. Always pass a value explicitly, even if it's the default "M".

Prerequisites before you write a line

You need Xcode 15 or later with an iOS 17 SDK for the SwiftUI parts, though the Core Image code itself compiles against much older deployment targets. The project needs no entitlements and no privacy usage strings—generating a QR code touches no protected resource. If you plan to let users save the generated image to their photo library, you'll need NSPhotoLibraryAddUsageDescription in Info.plist, but that's a separate concern from generation.

Import CoreImage and, for the UIKit rendering path, UIKit. If you're building a Swift package or a cross-platform module, guard the UIKit import behind #if canImport(UIKit) and provide an NSImage variant for macOS. The example below focuses on iOS but notes where the macOS path diverges.

Step one: model the generator as a small value type

Start with a struct that owns the configuration. Keeping configuration separate from rendering makes the code testable and lets you expose options in a settings screen later.

Two deliberate choices here. First, CorrectionLevel maps to exactly the four strings the filter accepts: "L", "M", "Q", "H". Passing anything else yields nil. Second, the CIContext is created once and stored. Creating a fresh context per render is a common performance mistake: context construction allocates GPU resources, and doing it in a table view cell or a live-preview loop will visibly stall the UI. A shared context is also thread-safe for rendering, so you can call it from a background queue.

The useSoftwareRenderer: false hint lets Core Image pick the GPU when available. On devices where the GPU path isn't suitable, Core Image falls back automatically; you don't need to branch.

Step two: encode the payload through Core Image

The encoding method takes a String, converts it to Data, and runs the filter.

The critical line is the transform. outputImage from the QR filter is tiny—each module is one pixel. If you hand that to a UIImageView that stretches it with the default interpolation, the modules blur at their boundaries and scanners struggle, especially at oblique angles or in low light. Scaling with a plain affine transform before rasterizing avoids that because Core Image's default sampling when you supply no custom kernel is nearest-neighbor for an integer scale. If you need arbitrary fractional scaling, apply a CISampleNearestNeighbor filter or pass a custom CIContext option; the affine transform alone is safe only for integer multiples. The example uses scale: 10, producing a 210-pixel image for the smallest symbol—plenty for on-screen display and reasonable for export.

The createCGImage(_:from:) call rasterizes into a CGImage you can wrap in UIImage(cgImage:) or draw into a Canvas. Rasterizing once and reusing the CGImage is cheaper than keeping CIImage around for repeated draws, because CIImage is a recipe, not pixels; each draw re-evaluates the graph.

Step three: render in SwiftUI with correct pixel alignment

SwiftUI will happily display a CGImage, but you have to prevent its default smoothing from softening module edges. The .interpolation(.none) modifier is the switch.

A few details earn their keep. Image(decorative:scale:) is used instead of Image(uiImage:) because it takes the CGImage directly without an intermediate UIImage, and it treats the asset as decorative by default—then the explicit accessibility label re-describes it, which is the right pattern for an image whose meaning is the underlying string. Setting .interpolation(.none) before .resizable() matters; view modifiers apply outside-in at render time, and placing interpolation after resizing still works in current SwiftUI, but keeping it adjacent to the Image makes the intent unmistakable and survives refactors. scaledToFit() lets the code grow to fill a card without distortion.

If you're displaying this in a list of many codes, cache the CGImage keyed by content and configuration. Regenerating on every body evaluation is wasteful—SwiftUI may re-run body frequently—and while encoding is fast, a list of fifty codes re-encoded on each scroll frame will drop frames.

Step four: color, contrast, and logo overlays without breaking scannability

Coloring is where well-intentioned generators fail. The filter outputs a grayscale image where dark modules are near-black and light modules are near-white. To recolor, you need a two-step Core Image pipeline: isolate the mask, then composite the foreground color through it onto the background color.

CIFilter.falseColor() maps two luminance endpoints to two colors, which suits a two-tone code exactly. The rule that governs whether the result scans is contrast, not hue. Dark modules must be substantially darker than light modules in perceived luminance, and the difference should be large—Apple's own guidance and the QR specification both imply that inverted codes (light modules on dark background) fail on many consumer scanners because they expect dark-on-light. Keep the foreground darker than the background, avoid mid-tone pairs like orange on yellow where luminance is close, and test with more than one scanner app.

Logos are more forgiving than people fear if error correction is high enough. When you place a logo, raise correction to .high ("H"), which tolerates roughly 30 percent of the codeword area being damaged or obscured. Then composite the logo image over the center using CISourceOverCompositing, keeping the covered area comfortably under that fraction. A logo covering 10–15 percent of the symbol area is conservative and scans reliably; pushing to 25 percent on a long URL at .low correction is how corners and quiet zones get destroyed. Preserve the quiet zone—the blank margin of four module widths around the code—by never letting the overlay or a background view touch the code's edge.

Step five: validate, export, and handle the failures

The single most common failure is passing a correction level string the filter doesn't recognize, which returns nil silently. Wrap the filter call in a small validation layer during development:

Assert the level is one of "L", "M", "Q", "H". Check the returned CIImage is non-nil before scaling. Log the payload length and chosen correction level; very long payloads at "H" may exceed the symbol's capacity.

Capacity is bounded. The QR specification caps a symbol at version 40, which holds 2,953 bytes in byte mode at correction level "L", less at higher levels. If you're encoding a long JSON blob or a large vCard, you may cross that line and the filter returns nil. The fix is not to force a higher version—Core Image doesn't expose that knob—but to shorten the payload: use a short redirect URL, compress the data, or split it. Testing with a payload near the limit catches this before users do.

Export to the photo library should go through UIImageWriteToSavedPhotosAlbum on a UIImage built from your largest scale (scale 20 or more), not from the on-screen thumbnail. Export as PNG, never JPEG. JPEG's block-based compression introduces ringing around module edges, and at small module sizes that ringing is what scanners misread. PNG preserves the sharp boundaries exactly.

Generation should run off the main actor if you're producing multiple codes or large-scale exports; encoding itself is quick, but rasterizing many images on the main thread during a UI transition will hitch. The CIContext is safe to share across queues for rendering.

One macOS divergence: replace UIImage with NSImage and use NSBitmapImageRep for export, but the Core Image pipeline is identical. On watchOS, Core Image availability is more limited historically, and the filter may not be present on very old watch hardware; test on your actual target before shipping.

What you get and when to reach for a third-party library

You now have a generator that handles plain text, URLs, colored output, and logo overlay with about 80 lines including the SwiftUI wrapper. It has no dependencies, updates with the OS, and gives you full control of rendering and contrast. What it doesn't give you is control over the QR version, mask pattern, or structured append, and it won't produce the newer Micro QR format. If your requirements are standard vCard, Wi-Fi, URL, or text codes—which covers the vast majority of apps—Core Image is the right tool.

Reach for a third-party package only when you need one of those missing controls, when you must support a platform where Core Image's QR filter is unavailable, or when you need decoding as well and want a single library for both directions. Core Image does have a CIDetector with the CIDetectorTypeQRCode type for reading, but it's less forgiving than dedicated decoders and Apple has not extended it with the newer Vision-based APIs. For reading, Vision's VNDetectBarcodesRequest is the modern path. For generating, the built-in filter is hard to beat on simplicity and stability.

The final check before shipping: print the code at a small size—2 centimeters square is realistic for packaging—and scan it with a phone camera from 20 centimeters in a dim room. If it reads, the contrast and scaling are right. If you've overlaid a logo, scan it at that same small size, because error correction headroom that feels generous on a large screen often isn't enough in print.