Camera access with no preview

I am trying to get a small test app working so that when I touch a button the app access the camera and takes a picture. I don’t need to show what the camera is looking at, i just want to take the picture and show it in an UIImageView.

I am getting an “objc_exception_throw” error. Code is below… Is this by chance covered in one of the video tutorials? If so you will pick up a new subscriber. :smiley:

    let cameraSession = AVCaptureSession()
    cameraSession.sessionPreset = AVCaptureSessionPresetMedium
    
    let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    
    do {
        let input = try AVCaptureDeviceInput(device: backCamera)
        cameraSession.canAddInput(input)
        let stillImageOutput = AVCaptureStillImageOutput()
        stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
        cameraSession.addOutput(stillImageOutput)
        let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
        
        stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
            let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
            let dataProvider = CGDataProviderCreateWithCFData(imageData)
            let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault)
            let image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
            self.takenPicture.image = image
        })
    } catch {
        return
    }

Did you call:

UIImagePickerControllerDelegate, UINavigationControllerDelegate in your viewcontroller?

It is working!

I did not need any delegates to fix my issue. But, I do appreciate the response!

What I did have to do is put all the AVFoundation setup code in viewDidLoad(), and start the camera “session” running. Then when you press the button it connects with the camera session and takes a picture.

After further reading the starting of the camera session takes some time. By breaking the process into two I allowed the slooooow camera startup process to finish before I asked for the picture!

If anyone is interested in the code let me know and I will post it.

2 Likes

lemme see your source code pls to try it for myself sir :slight_smile:

I don’t have any idea about it. But I would like to learn more. Thank you so much!