This demo shows use of SwiftQRCodeScanner using SwiftUI. This example uses Swift Package Manager as dependency manager.
ContentView.swift
import SwiftUI
import SwiftQRCodeScanner
struct ContentView: View {
@State private var isPresented = false
@State private var showExtraOptions = false
@State private var scannedValue: String = ""
@State private var textColor: Color = .black
@State private var result: Result<String, QRCodeError>?
var body: some View {
VStack(spacing: 30) {
Text(scannedValue)
.foregroundColor(textColor)
Button("Scan QR Code") {
self.isPresented = true
}
Button("Scan QR Code with Extra Options") {
self.showExtraOptions = true
self.isPresented = true
}
}
.sheet(isPresented: $isPresented) {
QRScanner(showExtraOptions: $showExtraOptions, result: self.$result)
}
.onChange(of: result) { newValue in
guard let unwrappedResult = newValue else { return }
switch unwrappedResult {
case .success(let qrCodeString):
self.scannedValue = qrCodeString
self.textColor = .black
case .failure(let qrCodeError):
self.scannedValue = qrCodeError.localizedDescription
self.textColor = .red
}
}
}
}
QRScanner.swift
import UIKit
import SwiftUI
import SwiftQRCodeScanner
struct QRScanner: UIViewControllerRepresentable {
@Binding var showExtraOptions: Bool
@Binding var result: Result<String, QRCodeError>?
@Environment(\.presentationMode) var presentationMode
func makeCoordinator() -> QRScanner.Coordinator {
return Coordinator(self)
}
func makeUIViewController(context: Context) -> QRCodeScannerController {
var picker: QRCodeScannerController?
if showExtraOptions {
var configuration = QRScannerConfiguration()
configuration.cameraImage = UIImage(named: "switch-camera-button")
configuration.flashOnImage = UIImage(named: "flash")
configuration.galleryImage = UIImage(named: "photos")
picker = QRCodeScannerController(qrScannerConfiguration: configuration)
} else {
picker = QRCodeScannerController()
}
picker!.delegate = context.coordinator
return picker!
}
func updateUIViewController(_ uiViewController: QRCodeScannerController, context: Context) {}
}
extension QRScanner {
class Coordinator: NSObject, QRScannerCodeDelegate {
@Environment(\.presentationMode) var presentationMode
var parent: QRScanner
init(_ parent: QRScanner) {
self.parent = parent
}
func qrScanner(_ controller: UIViewController, didScanQRCodeWithResult result: String) {
parent.result = .success(result)
parent.presentationMode.wrappedValue.dismiss()
}
func qrScanner(_ controller: UIViewController,
didFailWithError error: SwiftQRCodeScanner.QRCodeError) {
parent.result = .failure(error)
parent.presentationMode.wrappedValue.dismiss()
}
func qrScannerDidCancel(_ controller: UIViewController) {
print("QR Controller did cancel")
}
}
}