Skip to content

Commit 44ca43c

Browse files
authored
Merge pull request #196 from mattrubin/capture-session
Refactor AVCaptureSession creation
2 parents b9990ce + dcd7137 commit 44ca43c

File tree

2 files changed

+20
-22
lines changed

2 files changed

+20
-22
lines changed

Authenticator/Source/QRScanner.swift

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,28 +27,28 @@ import AVFoundation
2727

2828
protocol QRScannerDelegate: class {
2929
func handleDecodedText(_ text: String)
30-
func handleError(_ error: Error)
3130
}
3231

3332
class QRScanner: NSObject, AVCaptureMetadataOutputObjectsDelegate {
3433
weak var delegate: QRScannerDelegate?
3534
private let serialQueue = DispatchQueue(label: "QRScanner serial queue")
36-
private lazy var captureSession: AVCaptureSession? = {
37-
do {
38-
return try QRScanner.createCaptureSessionWithDelegate(self)
39-
} catch {
40-
DispatchQueue.main.async {
41-
self.delegate?.handleError(error)
42-
}
43-
return nil
44-
}
45-
}()
35+
private var captureSession: AVCaptureSession?
4636

47-
func start(_ completion: @escaping (AVCaptureSession?) -> Void) {
37+
func start(success: @escaping (AVCaptureSession) -> Void, failure: @escaping (Error) -> Void) {
4838
serialQueue.async {
49-
self.captureSession?.startRunning()
50-
DispatchQueue.main.async {
51-
completion(self.captureSession)
39+
do {
40+
let captureSession = try self.captureSession ?? QRScanner.createCaptureSessionWithDelegate(self)
41+
captureSession.startRunning()
42+
43+
self.captureSession = captureSession
44+
DispatchQueue.main.async {
45+
success(captureSession)
46+
}
47+
} catch {
48+
self.captureSession = nil
49+
DispatchQueue.main.async {
50+
failure(error)
51+
}
5252
}
5353
}
5454
}

Authenticator/Source/TokenScannerViewController.swift

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,11 @@ class TokenScannerViewController: UIViewController, QRScannerDelegate {
152152

153153
private func startScanning() {
154154
scanner.delegate = self
155-
scanner.start { captureSession in
156-
self.videoLayer.session = captureSession
157-
}
155+
scanner.start(success: { [weak self] captureSession in
156+
self?.videoLayer.session = captureSession
157+
}, failure: { [weak self] error in
158+
self?.dispatchAction(.scannerError(error))
159+
})
158160
}
159161

160162
private func showMissingAccessMessage() {
@@ -188,8 +190,4 @@ class TokenScannerViewController: UIViewController, QRScannerDelegate {
188190
}
189191
dispatchAction(.scannerDecodedText(text))
190192
}
191-
192-
func handleError(_ error: Error) {
193-
dispatchAction(.scannerError(error))
194-
}
195193
}

0 commit comments

Comments
 (0)