John Doe
John Doe

Reputation: 1609

How to time camera flash with image capture?

I want to make it so that my flash will time with when I take a picture, but not sure how. I've tried to do a NSTimer and NSSleep and other ways of timing it, but because sometimes the camera takes longer to focus and take the picture, than other times, it doesn't always get the flash exactly right. How would I accomplish this?

Here is how I do the flash...

func toggleFlash() {
    let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    if (device.hasTorch) {
        device.lockForConfiguration(nil)
        if (device.torchMode == AVCaptureTorchMode.On) {
            device.torchMode = AVCaptureTorchMode.Off
        } else {
            device.setTorchModeOnWithLevel(1.0, error: nil)
        }
        device.unlockForConfiguration()
    }
}

And here is how I take the picture...

func didPressTakePhoto(){

    if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
        videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
        stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
            (sampleBuffer, error) in

            if sampleBuffer != nil {

                var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                var dataProvider  = CGDataProviderCreateWithCFData(imageData)
                var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)

                var image:UIImage!

                if self.camera == true {
                    image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)

                } else {
                    image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.LeftMirrored)

                }

                self.tempImageView.image = image
                self.tempImageView.hidden = false

            }


        })
    }


}

Upvotes: 1

Views: 1260

Answers (1)

Gordon Childs
Gordon Childs

Reputation: 36169

In toggleFlash, you need to set

device.flashMode = .On

You're setting the torchMode.

Correcting this should make the flash go off at the right time during captureStillImageAsynchronouslyFromConnection.

Upvotes: 2

Related Questions