Scanning a QR code used to need a custom camera pipeline. Today iOS has VisionKit, which gives you DataScannerViewController: a ready-made camera screen that finds codes and text for you. It is a UIKit view controller, so this project also teaches the bridge between UIKit and SwiftUI: UIViewControllerRepresentable.
The most important lesson here is not the camera. It is that scanned content is untrusted input. A QR code can contain any text, including a link to a harmful site. The app therefore classifies the result, shows it, warns the user and only opens a link when they tap Open. Scanning needs a real iPhone, because the Simulator has no camera.
Concepts in this project
- DataScannerViewController: scans barcodes with highlighting, guidance and zoom built in. It needs iOS 16 or later and a supported device.
- UIViewControllerRepresentable: wraps a UIKit view controller for SwiftUI with
makeUIViewControllerandupdateUIViewController. - Coordinator: the object that receives delegate callbacks from UIKit and passes them to SwiftUI.
- Camera permission: a usage description in Info.plist and a request with
AVCaptureDevice.requestAccess. - Classifying results: an enum with link, Wi-Fi and text cases and a pure
classifyfunction. - Only http and https: other schemes such as javascript or tel are shown as plain text, never opened.
Create the project
- In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product QRScanner.
- In the Info tab add Privacy - Camera Usage Description with a plain sentence about why you use the camera (see the capabilities note).
- Delete the default ContentView.swift and the default @main file, then add the files below.
QRScanner/
QRApp.swift @main
QRResult.swift result enum + classifier
ScannerView.swift UIKit scanner wrapped for SwiftUI
QRScreen.swift permission, scanner, result card
QRScannerTests/
QRTests.swift
The code
`QRResult.swift`
import Foundation
enum QRResult: Equatable {
case link(URL)
case wifi(name: String, security: String)
case text(String)
var title: String {
switch self {
case .link: return "Link"
case .wifi: return "Wi-Fi network"
case .text: return "Text"
}
}
}
enum QRClassifier {
// Scanned content is untrusted input: it can be anything. We only decide what kind it is.
static func classify(_ raw: String) -> QRResult {
let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)
if text.uppercased().hasPrefix("WIFI:") {
let name = field("S", in: text) ?? "Unknown"
let security = field("T", in: text) ?? "none"
return .wifi(name: name, security: security)
}
if let url = URL(string: text),
let scheme = url.scheme?.lowercased(),
["http", "https"].contains(scheme),
url.host != nil {
return .link(url)
}
return .text(text)
}
// Reads one field from "WIFI:T:WPA;S:MyNetwork;P:secret;;"
private static func field(_ key: String, in text: String) -> String? {
for part in text.dropFirst(5).split(separator: ";") {
if part.hasPrefix(key + ":") {
return String(part.dropFirst(key.count + 1))
}
}
return nil
}
}
`ScannerView.swift`
import SwiftUI
import VisionKit
// Wraps UIKit's DataScannerViewController so SwiftUI can show it.
struct ScannerView: UIViewControllerRepresentable {
let onFound: (String) -> Void
func makeUIViewController(context: Context) -> DataScannerViewController {
let scanner = DataScannerViewController(
recognizedDataTypes: [.barcode(symbologies: [.qr])],
qualityLevel: .balanced,
recognizesMultipleItems: false,
isHighFrameRateTrackingEnabled: false,
isPinchToZoomEnabled: true,
isGuidanceEnabled: true,
isHighlightingEnabled: true
)
scanner.delegate = context.coordinator
return scanner
}
func updateUIViewController(_ scanner: DataScannerViewController, context: Context) {
if !scanner.isScanning {
try? scanner.startScanning()
}
}
func makeCoordinator() -> Coordinator {
Coordinator(onFound: onFound)
}
final class Coordinator: NSObject, DataScannerViewControllerDelegate {
let onFound: (String) -> Void
init(onFound: @escaping (String) -> Void) {
self.onFound = onFound
}
func dataScanner(_ dataScanner: DataScannerViewController,
didAdd addedItems: [RecognizedItem],
allItems: [RecognizedItem]) {
for item in addedItems {
if case .barcode(let code) = item, let text = code.payloadStringValue {
dataScanner.stopScanning()
onFound(text)
return
}
}
}
}
}
`QRScreen.swift`
import SwiftUI
import VisionKit
import AVFoundation
struct QRScreen: View {
@Environment(\.openURL) private var openURL
@State private var result: QRResult?
@State private var cameraAllowed = AVCaptureDevice.authorizationStatus(for: .video) == .authorized
var body: some View {
NavigationStack {
Group {
if !DataScannerViewController.isSupported {
message("This device cannot scan codes. Try a real iPhone.")
} else if let result {
card(for: result)
} else if cameraAllowed {
VStack {
ScannerView { text in
result = QRClassifier.classify(text)
}
Text("Point the camera at a QR code")
.padding()
}
} else {
VStack(spacing: 12) {
Text("Camera access is needed to scan codes. The picture never leaves your phone.")
.multilineTextAlignment(.center)
Button("Allow camera") {
AVCaptureDevice.requestAccess(for: .video) { granted in
DispatchQueue.main.async { cameraAllowed = granted }
}
}
.buttonStyle(.borderedProminent)
}
.padding()
}
}
.navigationTitle("QR Scanner")
}
}
private func message(_ text: String) -> some View {
Text(text).multilineTextAlignment(.center).padding()
}
private func card(for result: QRResult) -> some View {
VStack(alignment: .leading, spacing: 12) {
Text(result.title).font(.title2.bold())
switch result {
case .link(let url):
Text(url.absoluteString).textSelection(.enabled)
Text("Open only links you trust.").font(.footnote).foregroundStyle(.secondary)
Button("Open") { openURL(url) }
.buttonStyle(.borderedProminent)
case .wifi(let name, let security):
Text("Name: \(name)")
Text("Security: \(security)")
case .text(let text):
Text(text).textSelection(.enabled)
}
Button("Scan again") { self.result = nil }
.buttonStyle(.bordered)
Spacer()
}
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
}
}
`QRApp.swift`
import SwiftUI
@main
struct QRApp: App {
var body: some Scene {
WindowGroup {
QRScreen()
}
}
}
`QRTests.swift (in the tests target)`
import Testing
import Foundation
@testable import QRScanner
struct QRTests {
@Test func webAddressIsALink() {
#expect(QRClassifier.classify("https://example.com/a?b=1") == .link(URL(string: "https://example.com/a?b=1")!))
}
@Test func otherSchemesAreOnlyText() {
#expect(QRClassifier.classify("javascript:alert(1)") == .text("javascript:alert(1)"))
#expect(QRClassifier.classify("tel:+911234567890") == .text("tel:+911234567890"))
}
@Test func wifiCodeIsRecognised() {
#expect(QRClassifier.classify("WIFI:T:WPA;S:HomeNet;P:secret;;") == .wifi(name: "HomeNet", security: "WPA"))
}
@Test func plainTextStaysText() {
#expect(QRClassifier.classify(" hello world ") == .text("hello world"))
}
}
Walkthrough
QRClassifier.classify is the safety layer. It trims the text. If the text starts with WIFI: it reads the network name and security type from the fields. Otherwise it tries to make a URL and accepts it only when the scheme is http or https and a host exists. Everything else, including javascript: and tel: text, becomes plain text. Because the function is pure, three of the four tests need no camera at all.
ScannerView conforms to UIViewControllerRepresentable. makeUIViewController builds the scanner for QR codes only, with guidance and highlighting on, and sets the coordinator as its delegate. updateUIViewController starts scanning if it is not already running. SwiftUI calls it whenever the view's state changes, so the isScanning check prevents starting twice.
The Coordinator implements DataScannerViewControllerDelegate. When items are added, it looks for a barcode with a text payload, stops scanning and calls onFound. Stopping first matters: otherwise the same code could be reported again and again while it stays in view.
QRScreen decides what to show with a chain of conditions. If the device is not supported it says so. If there is a result it shows the card. If the camera is allowed it shows the scanner. Otherwise it explains why the camera is needed and offers an Allow camera button. Explaining before asking improves the chance the user says yes.
On the result card, links show the full address, a reminder to open only trusted links and an Open button that calls openURL. Showing the address lets a careful user spot a lookalike domain. Scan again clears the result, which removes the card and brings back the scanner.
How it works
- The screen checks support and permission, then shows the scanner.
- The scanner reports the first QR code and stops scanning.
classifyturns the text into a link, a Wi-Fi description or text.- The card shows the result. A link opens only after a tap.
Expected output
On a real iPhone, the first launch asks to allow the camera. After you allow it, you see the live camera with a highlight guide and the line "Point the camera at a QR code". Hold a QR code that contains a web address in front of it: the camera stops and a card titled Link appears with the address, the reminder, an Open button and Scan again. A QR code with plain words shows a Text card. In the Simulator the screen says the device cannot scan codes. The four tests pass on any Mac.
Your task
- Build on a real iPhone and scan a link, plain text and a Wi-Fi code.
- Add a history list saved with SwiftData.
- Add the torch with AVCaptureDevice.torchMode.
- Scan more than QR codes by adding more symbologies, and show the type.
How to check it worked
- The app never opens a link without a tap.
- Denied permission leaves a clear Allow camera path.
- You can explain what a Coordinator is for.
Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.