twostraws / CodeScanner

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

The torch flashes once briefly before lighting up continuously. #70

Closed s33k2k22 closed 2 years ago

s33k2k22 commented 2 years ago

Hello all, first of all thanks for this great code!

I just have a little problem with the isTorchOn Option.

CodeScannerView(codeTypes: [.qr], showViewfinder: true, isTorchOn: true)

For me, the torch flashes once briefly before lighting up continuously. Is this a bug? Is there a way to create a button on the view to turn the torch on or off when scanning the QR code?

thanks a lot!

calebmarquart commented 2 years ago

To create a button to turn on the flashlight put CodeScannerView inside a ZStack with a button positioned somewhere on top (if that's what you want). Then just create a @State variable for if the torch is on and then pass that as a binding into the parameter isTorchOn. The button can then toggle the variable and it will automatically update the torch.

nathanfallet commented 2 years ago

You can do something like this:

struct ScannerView: View {

    @State var torchIsOn: Bool = false
    @State var isGalleryPresented: Bool = false

    var body: some View {
        ZStack {
            CodeScannerView(
                codeTypes: [.qr],
                scanMode: .oncePerCode,
                isTorchOn: $torchIsOn,
                isGalleryPresented: $isGalleryPresented,
                completion: { _ in }
            )
            .ignoresSafeArea()
            VStack {
                Spacer()
                HStack {
                    Button(action: toggleTorch) {
                        Image(systemName: torchIsOn ? "bolt.fill" : "bolt.slash.fill")
                            .imageScale(.large)
                            .frame(width: 40, height: 40)
                            .foregroundColor(torchIsOn ? Color.yellow : Color.accentColor)
                            .padding()
                    }
                    .background(Color(.systemGray6))
                    .cornerRadius(10)
                    Button(action: openGallery) {
                        Image(systemName: "photo.fill")
                            .imageScale(.large)
                            .frame(width: 40, height: 40)
                            .padding()
                    }
                    .background(Color(.systemGray6))
                    .cornerRadius(10)
                }
            }
            .padding()
        }
        .navigationTitle(Text("scanner_title"))
    }

    func toggleTorch() {
        torchIsOn.toggle()
    }

    func openGallery() {
        isGalleryPresented.toggle()
    }

}