simple_code
simple_code

Reputation: 767

Turn on torch/flashlight and camera at the same time on iPhone X

Is there a way to keep the flashlight on while AVCaptureSession is running on video mode on the iPhone X?

I have Swift 4 code that turns on the flashlight then starts getting video frames from the camera. I know it works for iPhone 4,5 and 6. But with an iPhone X the flashlight does not come on when I start the capture session.

session = AVCaptureSession()
if self.session.canSetSessionPreset(AVCaptureSession.Preset.inputPriority) {
    self.session.sessionPreset = .inputPriority
}
//This is the wide angle camera device
camera = AVCaptureDevice.default(for: AVMediaType.video)
//I could also use telephoto, same problem
//camera = AVCaptureDevice.default(.builtInTelephotoCamera, for: AVMediaType.video, position: .unspecified)
if camera == nil {
    return
}
if self.camera.isTorchModeSupported(.on) {
    camera.activeFormat = selectBestFormat(camera.formats)
    camera.torchMode = .on
    try? camera.setTorchModeOn(level: 1.0)
    camera.unlockForConfiguration()
}

let cameraInput = try! AVCaptureDeviceInput(device: self.camera)


let videoOutput = AVCaptureVideoDataOutput()
let captureQueue = DispatchQueue(label: "captureQueue")
videoOutput.setSampleBufferDelegate(self, queue: captureQueue)
videoOutput.videoSettings = [
    (kCVPixelBufferPixelFormatTypeKey as AnyObject) as! AnyHashable as! String : Int(kCVPixelFormatType_32BGRA)
]

self.session.addInput(cameraInput)
self.session.addOutput(videoOutput)
//If I don't start the session the torch is on 
self.session.startRunning()

This question has the same problem. The problem in my case is that the flashlight turns off as soon as the AVCaptureSession starts.

I have tried turning the flashlight on after starting the session, I have tried a number of different camera configurations. I have also tried using the two different camera lenses. For all those configurations the light goes off.

If there is no solution, please let me know if there is a bug logged for this. Or I will log one.

Upvotes: 2

Views: 4264

Answers (1)

Tintenklecks
Tintenklecks

Reputation: 507

had the same problem. Seems to be a bug in iOS 11/iPhone X

I found a workaround ... not very elegant, but works ;-)

    if let device = captureDevice {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.setTorchLevel(device: device, to: 0)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.setTorchLevel(device: device, to: 1)
        }
    }

Even on the iPhone the "Have you tried to turn it off and on again" works

Upvotes: 6

Related Questions