Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVCaptureSession freezes when torch is turned on

We have barcode scanning functionality in our iOS app and we give the customer the ability to toggle the torch on and off as needed. On the iPhone X (and only on the iPhone X) when the AvCaptureSession is running and the torch is enabled, the video capture on the screen freezes. As soon as the torch is turned off again the video capture starts again. Has anyone run into this? I can't seem to find anything that points to a work around. Wondering if this a iPhone X bug?

like image 815
sully77 Avatar asked Sep 12 '18 14:09

sully77


1 Answers

I ran into this issue. After some experimentation, it turned out that obtaining the device to configure the torch must be done in the exact same way that you obtain the device when you configure your AVCaptureSession. E.G.:

    let captureSession = AVCaptureSession()
    let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera], mediaType: AVMediaType.video, position: .back)

        guard let captureDevice = deviceDiscoverySession.devices.first else {
            print("Couldn't get a camera")
            return
        }
     do {
            let input = try AVCaptureDeviceInput(device: captureDevice)
            captureSession!.addInput(input)
        } catch {
            print(error)
            return
        }

Use that exact method for obtaining the device when toggling the torch (flashlight) on and off. In this case, the lines:

let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera], mediaType: AVMediaType.video, position: .back)

guard let device = deviceDiscoverySession.devices.first

Example:

func toggleTorch() {

    let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera], mediaType: AVMediaType.video, position: .back)

    guard let device = deviceDiscoverySession.devices.first
        else {return}

    if device.hasTorch {
        do {
            try device.lockForConfiguration()
            let on = device.isTorchActive
            if on != true && device.isTorchModeSupported(.on) {
                try device.setTorchModeOn(level: 1.0)
            } else if device.isTorchModeSupported(.off){
                device.torchMode = .off
            } else {
                print("Torch mode is not supported")
            }
            device.unlockForConfiguration()
        } catch {
            print("Torch could not be used")
        }
    } else {
        print("Torch is not available")
    }
}

I realize some code may be superfluous in the toggleTorch function, but I'm leaving it. Hope this helps.

like image 158
smakus Avatar answered Oct 28 '22 03:10

smakus