twostraws / CodeScanner

A SwiftUI view that is able to scan barcodes, QR codes, and more, and send back what was found.
MIT License
1.03k stars 295 forks source link

Freeze when Turn on the flashlight #140

Open ximplia-paolo-pasianot opened 5 months ago

ximplia-paolo-pasianot commented 5 months ago

Good morning, I want to preface by saying that I'm not an experienced Swift and iOS programmer, but I think I've found a bug with the flashlight. I've implemented the QR code reading library and added a button to toggle the flashlight on and off. However, when I activate the flashlight, the QR code reading screen freezes.

// QR Code part
CodeScannerView(
      codeTypes: [.qr],
      simulatedData: "result",
      completion: { result in
          switch result {
          case .success(let result):
              self.ticketScan.handleEvent(event: .OnCodeFound(ticket: result.string))
              break
          case .failure(let error):
              self.ticketScan.handleEvent(event: .OnError(.QRCodeScan))
          }
      }
)

//Toggle Flash
private func toggleFlash() {
        guard let device = AVCaptureDevice.default(for: .video) else { return }

        if device.hasTorch {
            do {
                try device.lockForConfiguration()
                if device.torchMode == .on {
                    device.torchMode = .off
                } else {
                    device.torchMode = .on
                }
                device.unlockForConfiguration()
            } catch {
                self.ticketScan.handleEvent(event: .OnError(.NoCamera))
            }
        } else {
            self.ticketScan.handleEvent(event: .OnError(.NoFlash))
        }
    }

Thank you very much for the time you've dedicated to me.

Ramon4ngel commented 2 months ago

Hello,

I am new in IOS too.

I think the QR code reading screen freezes because your code takes control of the Camere Hardware, and the CodeScannerView loses the Camera control, so CodeScannerView freezes.

The Flashlight capability is implemented in CodeScannerView. Try this:

struct QRCodeScannerView: View { .... @State private var isFlashlightOn = false .... .sheet(isPresented: $isPresentingScanner) { CodeScannerView(codeTypes: [.qr], showViewfinder: true, isTorchOn: isFlashlightOn) ... Button("Flashlight"){ if isFlashlightOn { isFlashlightOn = false }else{ isFlashlightOn = true } }

Adding a button in the sheet works fine for me.