How to Generate a Basic QR Code with EFQRCode: A Complete Swift Guide
To generate a basic QR code with EFQRCode, initialize the EFQRCode.Generator class with your text content and call toImage(width:) or toPNGData(width:) to produce a rasterized output.
EFQRCode is a lightweight, pure-Swift QR code generation library that wraps the QRCodeSwift engine to provide a clean API for iOS, macOS, tvOS, watchOS, and visionOS. When you need to generate a basic QR code with EFQRCode, the library handles UTF-8 encoding, error correction, and platform-specific image rendering automatically through the EFQRCode.Generator class defined in Source/EFQRCode+Generator.swift.
EFQRCode Architecture for Basic Generation
The library delegates matrix encoding to QRCodeSwift while managing style and rasterization internally. For a basic black-on-white QR code, the system uses the default EFQRCodeStyleBasic implementation.
| Component | Source File | Role in Basic Generation |
|---|---|---|
| Entry Point | Source/EFQRCode+Generator.swift |
EFQRCode.Generator accepts text, encodes data, and exposes toImage() and toPNGData() methods. |
| Encoding Engine | QRCode.swift (QRCodeSwift) |
Builds the QR matrix using the default high error-correction level (.h). |
| Default Style | Source/Styles/EFQRCodeStyleBasic.swift |
Renders standard black modules on a white background when no custom style is provided. |
| Error Handling | Source/Type/EFQRCodeError.swift |
Defines EFQRCodeError for encoding failures, data overflow, or rasterization issues. |
When you generate a basic QR code with EFQRCode, the generator first converts your string to Data using UTF-8, passes it to the QRCodeSwift encoder, then asks the basic style to produce an SVG representation. SwiftDraw rasterizes that SVG into a UIImage (iOS) or NSImage (macOS) at your specified width.
Step-by-Step Implementation
Minimal Synchronous Generation
The simplest way to generate a basic QR code with EFQRCode requires only two lines of code after initialization.
import EFQRCode
import UIKit
do {
// Initialize the generator with your content
let generator = try EFQRCode.Generator("https://github.com/efprefix/efqrcode")
// Render to UIImage at 300 points width
let qrImage = try generator.toImage(width: 300)
// Display in a UIImageView
imageView.image = qrImage
} catch {
print("Generation failed: \(error)")
}
Key implementation details:
- The constructor defaults to high error correction (
.h), ensuring the QR code remains readable even if partially obscured. - Omitting the style parameter automatically selects
EFQRCodeStyleBasic, producing the classic black-on-white appearance. toImage(width:)returns a platform-native image type (UIImageon iOS,NSImageon macOS).
Exporting to PNG Format
To generate a basic QR code with EFQRCode and save it as a file, use toPNGData(width:) to obtain raw PNG bytes.
import EFQRCode
func saveQRCode(text: String, filename: String) {
do {
let generator = try EFQRCode.Generator(text)
let pngData = try generator.toPNGData(width: 512)
let url = FileManager.default
.urls(for: .documentDirectory, in: .userDomainMask)
.first!
.appendingPathComponent("\(filename).png")
try pngData.write(to: url)
print("Saved QR code to \(url)")
} catch {
print("Failed to save: \(error)")
}
}
This approach bypasses manual image conversion; toPNGData handles rasterization and PNG encoding internally via the generator’s rendering pipeline.
Handling Encoding Errors
When you generate a basic QR code with EFQRCode, encoding failures throw EFQRCodeError. Explicit error handling allows you to distinguish between data overflow, text encoding issues, or rasterization failures.
import EFQRCode
do {
// Attempt to encode an excessively large string
let largeText = String(repeating: "X", count: 10_000)
let _ = try EFQRCode.Generator(largeText)
} catch let error as EFQRCodeError {
switch error {
case .dataTooLarge(let maxCapacity):
print("Input exceeds QR capacity. Maximum bytes allowed: \(maxCapacity)")
case .text(let text, let encoding):
print("Cannot encode '\(text)' using \(encoding)")
default:
print("EFQRCode error: \(error.localizedDescription)")
}
} catch {
print("Unexpected error: \(error)")
}
The dataTooLarge case specifically reports the maximum byte capacity for the selected error-correction level, helping you adjust input size accordingly.
Key Source Files in the EFQRCode Repository
Understanding the source structure helps when debugging or extending basic generation functionality.
-
Source/EFQRCode+Generator.swift– Contains theEFQRCode.Generatorclass, implementingtoImage(),toPNGData(), and the internal encoding pipeline that interfaces with QRCodeSwift. -
Source/Styles/EFQRCodeStyleBasic.swift– Defines the default visual style used when you generate a basic QR code with EFQRCode, rendering standard black modules on a white background. -
Source/EFQRCode.swift– The public façade that exposes static members includingGeneratorandRecognizer, providing the clean API entry point. -
Source/Type/EFQRCodeError.swift– Centralized error definitions includingdataTooLarge,text, and rasterization failures thrown during generation.
Summary
- Entry Point: Use
EFQRCode.Generator(_ text: String)to initialize the generator with UTF-8 content. - Default Behavior: Omitting a style parameter automatically applies
EFQRCodeStyleBasic, producing a standard black-on-white QR code with high error correction. - Output Methods: Call
toImage(width:)for platform-native images (UIImage/NSImage) ortoPNGData(width:)for raw PNG bytes suitable for file storage. - Error Handling: Wrap generation in
do-catchblocks to handleEFQRCodeErrorcases such asdataTooLargewhen input exceeds QR capacity. - Core Files: The generation logic resides in
Source/EFQRCode+Generator.swift, with styling defined inSource/Styles/EFQRCodeStyleBasic.swift.
Frequently Asked Questions
What is the default error correction level when generating a basic QR code with EFQRCode?
The EFQRCode.Generator constructor defaults to the high error correction level (.h). This ensures the generated QR code remains scannable even if up to 30% of the code is obscured or damaged, making it ideal for basic branding overlays or physical printing.
How do I save a generated QR code as a PNG file using EFQRCode?
Use the toPNGData(width:) method on your generator instance to obtain Data containing the PNG representation. Write this data to disk using FileManager and write(to:) on the data object. This bypasses manual image conversion and handles rasterization internally via SwiftDraw.
What error types does EFQRCode throw when generation fails?
EFQRCode throws EFQRCodeError, an enum defined in Source/Type/EFQRCodeError.swift. Common cases include .dataTooLarge(maxCapacity:) when input exceeds the QR standard's byte limit for the selected error level, and .text(_:encoding:) when the provided string cannot be encoded in the specified character set.
Which Swift platforms support EFQRCode QR code generation?
EFQRCode supports iOS, macOS, tvOS, watchOS, and visionOS. The toImage(width:) method returns a UIImage on iOS/tvOS/watchOS/visionOS and an NSImage on macOS, ensuring platform-native image types across all supported operating systems.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →