8

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?

sully77
  • 357
  • 3
  • 11
  • Does someone has a solution for this? I ran into the same problem and can't figure it out. For me it happens on iPhone X (iOS 12) and iPhone 7 Plus (iOS 11.3.1). But it works fine on iPhone 6 Plus (iOS 9.3.1) – Martin Nov 16 '18 at 14:16

1 Answers1

12

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.

smakus
  • 1,107
  • 10
  • 11