Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

QRCodeScannerView.swift

332 lines11.0 KB

1@preconcurrency import AVFoundation
2import SwiftUI
3import UIKit
4​
5struct QRCodeScannerView: View {
6 let onScan: (String) -> Void
7 let onCancel: () -> Void
8 let onPaste: () -> Void
9​
10 @State private var availability: QRScannerAvailability = .checking
11​
12 var body: some View {
13 ZStack {
14 Color.black.ignoresSafeArea()
15​
16 QRScannerCameraView(
17 availability: $availability,
18 onScan: onScan
19 )
20 .ignoresSafeArea()
21​
22 LinearGradient(
23 colors: [.black.opacity(0.7), .clear, .black.opacity(0.8)],
24 startPoint: .top,
25 endPoint: .bottom
26 )
27 .ignoresSafeArea()
28 .allowsHitTesting(false)
29​
30 VStack(spacing: 0) {
31 HStack {
32 Button("Cancel", action: onCancel)
33 .font(.body.weight(.semibold))
34 Spacer()
35 Text("Scan QR code")
36 .font(.headline)
37 Spacer()
38 Button("Cancel", action: onCancel)
39 .hidden()
40 }
41 .padding(.horizontal, 20)
42 .frame(height: 56)
43​
44 Spacer()
45​
46 if availability == .ready {
47 scannerFrame
48 Text("Point your camera at the QR code shown by T3 Code.")
49 .font(T3Typography.threadBody)
50 .foregroundStyle(.white.opacity(0.78))
51 .multilineTextAlignment(.center)
52 .padding(.top, 28)
53 } else {
54 unavailableContent
55 }
56​
57 Spacer()
58​
59 Button {
60 onPaste()
61 } label: {
62 Label("Paste connection link", systemImage: "doc.on.clipboard")
63 .font(.body.weight(.semibold))
64 .frame(maxWidth: .infinity)
65 .frame(minHeight: 50)
66 }
67 .buttonStyle(.bordered)
68 .tint(.white)
69 .padding(.horizontal, 28)
70 .padding(.bottom, 24)
71 }
72 }
73 .preferredColorScheme(.dark)
74 }
75​
76 private var scannerFrame: some View {
77 RoundedRectangle(cornerRadius: 24)
78 .stroke(Color.white.opacity(0.9), lineWidth: 3)
79 .frame(width: 252, height: 252)
80 .overlay(alignment: .topLeading) {
81 Image(systemName: "viewfinder")
82 .resizable()
83 .frame(width: 282, height: 282)
84 .offset(x: -15, y: -15)
85 .foregroundStyle(.white)
86 }
87 .accessibilityHidden(true)
88 }
89​
90 @ViewBuilder
91 private var unavailableContent: some View {
92 switch availability {
93 case .checking:
94 ProgressView()
95 .controlSize(.large)
96 .accessibilityLabel("Checking camera")
97 case .ready:
98 EmptyView()
99 case .denied:
100 VStack(spacing: 14) {
101 Image(systemName: "camera.fill")
102 .font(.system(size: 34))
103 Text("Camera access is off")
104 .font(.title3.bold())
105 Text("Allow camera access in Settings to scan a pairing code.")
106 .font(T3Typography.threadBody)
107 .foregroundStyle(.white.opacity(0.78))
108 .multilineTextAlignment(.center)
109 Button("Open Settings") {
110 guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
111 UIApplication.shared.open(url)
112 }
113 .buttonStyle(.borderedProminent)
114 .tint(.white)
115 .foregroundStyle(.black)
116 }
117 .padding(.horizontal, 36)
118 case .unavailable:
119 VStack(spacing: 14) {
120 Image(systemName: "camera.slash.fill")
121 .font(.system(size: 34))
122 Text("Camera unavailable")
123 .font(.title3.bold())
124 Text("Paste the connection link instead.")
125 .font(T3Typography.threadBody)
126 .foregroundStyle(.white.opacity(0.78))
127 }
128 }
129 }
131​
132private enum QRScannerAvailability: Equatable {
133 case checking
134 case ready
135 case denied
136 case unavailable
138​
139private struct QRScannerCameraView: UIViewControllerRepresentable {
140 @Binding var availability: QRScannerAvailability
141 let onScan: (String) -> Void
142​
143 func makeCoordinator() -> Coordinator {
144 Coordinator(availability: $availability, onScan: onScan)
145 }
146​
147 func makeUIViewController(context: Context) -> QRScannerViewController {
148 let controller = QRScannerViewController()
149 context.coordinator.attach(to: controller)
150 return controller
151 }
152​
153 func updateUIViewController(_ controller: QRScannerViewController, context: Context) {}
154​
155 static func dismantleUIViewController(
156 _ controller: QRScannerViewController,
157 coordinator: Coordinator
158 ) {
159 controller.stop()
160 }
161​
162 @MainActor
163 final class Coordinator: NSObject, AVCaptureMetadataOutputObjectsDelegate {
164 private var availability: Binding<QRScannerAvailability>
165 private let onScan: (String) -> Void
166 private weak var controller: QRScannerViewController?
167 private var didScan = false
168​
169 init(
170 availability: Binding<QRScannerAvailability>,
171 onScan: @escaping (String) -> Void
172 ) {
173 self.availability = availability
174 self.onScan = onScan
175 }
176​
177 func attach(to controller: QRScannerViewController) {
178 self.controller = controller
179 controller.prepare(delegate: self) { [weak self] nextAvailability in
180 self?.availability.wrappedValue = nextAvailability
181 }
182 }
183​
184 nonisolated func metadataOutput(
185 _ output: AVCaptureMetadataOutput,
186 didOutput metadataObjects: [AVMetadataObject],
187 from connection: AVCaptureConnection
188 ) {
189 guard let value = (metadataObjects.first as? AVMetadataMachineReadableCodeObject)?
190 .stringValue
191 else {
192 return
193 }
194 Task { @MainActor [weak self] in
195 guard let self, !didScan else { return }
196 didScan = true
197 controller?.stop()
198 UINotificationFeedbackGenerator().notificationOccurred(.success)
199 onScan(value)
200 }
201 }
202 }
204​
205@MainActor
206private final class QRScannerViewController: UIViewController {
207 private let captureSession = AVCaptureSession()
208 private let sessionQueue = DispatchQueue(label: "codes.t3.swift-ios.qr-scanner")
209 private var previewLayer: AVCaptureVideoPreviewLayer?
210 private var metadataDelegate: AVCaptureMetadataOutputObjectsDelegate?
211 private var availabilityChanged: (@MainActor (QRScannerAvailability) -> Void)?
212 private var isConfiguring = false
213 private var isRequestingAuthorization = false
214​
215 override func viewDidLoad() {
216 super.viewDidLoad()
217 view.backgroundColor = .black
218 }
219​
220 // SwiftUI does not reliably dismantle a representable the moment its
221 // fullScreenCover dismisses, and backgrounding never dismantles it, so
222 // stop the camera on disappear and resume it when the view returns.
223 override func viewDidDisappear(_ animated: Bool) {
224 super.viewDidDisappear(animated)
225 stop()
226 }
227​
228 override func viewWillAppear(_ animated: Bool) {
229 super.viewWillAppear(animated)
230 guard previewLayer != nil else {
231 refreshAuthorization()
232 return
233 }
234 let session = captureSession
235 sessionQueue.async {
236 if !session.isRunning {
237 session.startRunning()
238 }
239 }
240 }
241​
242 override func viewDidLayoutSubviews() {
243 super.viewDidLayoutSubviews()
244 previewLayer?.frame = view.bounds
245 }
246​
247 func prepare(
248 delegate: AVCaptureMetadataOutputObjectsDelegate,
249 availabilityChanged: @escaping @MainActor (QRScannerAvailability) -> Void
250 ) {
251 metadataDelegate = delegate
252 self.availabilityChanged = availabilityChanged
253 refreshAuthorization()
254 }
255​
256 private func refreshAuthorization() {
257 guard let metadataDelegate, let availabilityChanged else { return }
258 switch AVCaptureDevice.authorizationStatus(for: .video) {
259 case .authorized:
260 configure(delegate: metadataDelegate, availabilityChanged: availabilityChanged)
261 case .notDetermined:
262 guard !isRequestingAuthorization else { return }
263 isRequestingAuthorization = true
264 AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
265 Task { @MainActor in
266 guard let self else { return }
267 self.isRequestingAuthorization = false
268 guard granted else {
269 self.availabilityChanged?(.denied)
270 return
271 }
272 self.refreshAuthorization()
273 }
274 }
275 case .denied, .restricted:
276 availabilityChanged(.denied)
277 @unknown default:
278 availabilityChanged(.unavailable)
279 }
280 }
281​
282 func stop() {
283 let session = captureSession
284 sessionQueue.async {
285 if session.isRunning {
286 session.stopRunning()
287 }
288 }
289 }
290​
291 private func configure(
292 delegate: AVCaptureMetadataOutputObjectsDelegate,
293 availabilityChanged: @escaping @MainActor (QRScannerAvailability) -> Void
294 ) {
295 guard previewLayer == nil, !isConfiguring else { return }
296 isConfiguring = true
297 defer { isConfiguring = false }
298 guard let camera = AVCaptureDevice.default(for: .video),
299 let input = try? AVCaptureDeviceInput(device: camera),
300 captureSession.canAddInput(input)
301 else {
302 availabilityChanged(.unavailable)
303 return
304 }
305​
306 let output = AVCaptureMetadataOutput()
307 guard captureSession.canAddOutput(output) else {
308 availabilityChanged(.unavailable)
309 return
310 }
311​
312 captureSession.beginConfiguration()
313 captureSession.sessionPreset = .high
314 captureSession.addInput(input)
315 captureSession.addOutput(output)
316 output.setMetadataObjectsDelegate(delegate, queue: .main)
317 output.metadataObjectTypes = [.qr]
318 captureSession.commitConfiguration()
319​
320 let preview = AVCaptureVideoPreviewLayer(session: captureSession)
321 preview.videoGravity = .resizeAspectFill
322 preview.frame = view.bounds
323 view.layer.insertSublayer(preview, at: 0)
324 previewLayer = preview
325 availabilityChanged(.ready)
326​
327 let session = captureSession
328 sessionQueue.async {
329 session.startRunning()
330 }
331 }