QR code: Degrade gracefully when running on the simulator or on a device without a camera

Signed-off-by: Roopesh Chander <roop@roopc.net>
This commit is contained in:
Roopesh Chander 2018-11-01 02:14:30 +05:30
parent 95ad752d65
commit b96e5ae563
1 changed files with 6 additions and 5 deletions

View File

@ -13,7 +13,7 @@ class QRScanViewController: UIViewController {
weak var delegate: QRScanViewControllerDelegate? weak var delegate: QRScanViewControllerDelegate?
var captureSession: AVCaptureSession? = AVCaptureSession() var captureSession: AVCaptureSession? = AVCaptureSession()
let metadataOutput = AVCaptureMetadataOutput() let metadataOutput = AVCaptureMetadataOutput()
var previewLayer: AVCaptureVideoPreviewLayer! var previewLayer: AVCaptureVideoPreviewLayer?
override func viewDidLoad() { override func viewDidLoad() {
super.viewDidLoad() super.viewDidLoad()
@ -50,10 +50,11 @@ class QRScanViewController: UIViewController {
metadataOutput.setMetadataObjectsDelegate(self, queue: .main) metadataOutput.setMetadataObjectsDelegate(self, queue: .main)
metadataOutput.metadataObjectTypes = [.qr] metadataOutput.metadataObjectTypes = [.qr]
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = view.layer.bounds previewLayer.frame = view.layer.bounds
previewLayer.videoGravity = .resizeAspectFill previewLayer.videoGravity = .resizeAspectFill
view.layer.insertSublayer(previewLayer, at: 0) view.layer.insertSublayer(previewLayer, at: 0)
self.previewLayer = previewLayer
} }
override func viewWillAppear(_ animated: Bool) { override func viewWillAppear(_ animated: Bool) {
@ -75,7 +76,7 @@ class QRScanViewController: UIViewController {
override func viewDidLayoutSubviews() { override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews() super.viewDidLayoutSubviews()
if let connection = previewLayer.connection { if let connection = previewLayer?.connection {
let currentDevice: UIDevice = UIDevice.current let currentDevice: UIDevice = UIDevice.current
@ -100,8 +101,8 @@ class QRScanViewController: UIViewController {
} }
} }
} }
previewLayer.frame = self.view.bounds previewLayer?.frame = self.view.bounds
} }
func scanDidComplete(withCode code: String) { func scanDidComplete(withCode code: String) {