         }
         
         q.async {
-            let captureDevice = AVCaptureDevice.default(for: .video)!
-            let input = try! AVCaptureDeviceInput(device: captureDevice)
-            captureSession.addInput(input)
-            let previewLayer = self.setupPreviewLayer(session: captureSession)
-            self.setupMetadataOutput()
-            captureSession.startRunning()
-            
-            DispatchQueue.main.async {
-                self.videoPreviewLayer = previewLayer
-                self.isScanning = true
+            do {
+                captureSession.beginConfiguration()
+                let captureDevice = AVCaptureDevice.default(for: .video)!
+                let input = try AVCaptureDeviceInput(device: captureDevice)
+                captureSession.addInput(input)
+                let previewLayer = self.setupPreviewLayer(session: captureSession)
+                self.setupMetadataOutput()
+                captureSession.commitConfiguration()
+                captureSession.startRunning()
+                
+                DispatchQueue.main.async {
+                    self.videoPreviewLayer = previewLayer
+                    self.isScanning = true
+                    completion?(nil)
+                }
+            } catch {
+                captureSession.commitConfiguration()
+                completion?(error)
             }
         }
     }

        super.removeFromSuperview()
    }
    
    public func startReading() throws {
        if isFreezing && !isScanning {
            resumeReading()
        }
        
        self.captureSession = AVCaptureSession()

        
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
        
        if let readableObj = obj as? AVMetadataMachineReadableCodeObject {
            guard let str = readableObj.stringValue else {
                error = "Invalid Code"
                return
            }
            code = str
        } else {
            error = "Wrong code type or invalid code"
        }
    }
}
