1

Does anybody know how I can get a live camera feed into an UIImageView?

I have a custom UI where I need to show the camera feed (front facing camera) so I cannot use the UIImagePickerControl.

AMIC MING
  • 6,306
  • 6
  • 46
  • 62
CyberK
  • 1,568
  • 3
  • 31
  • 44

1 Answers1

4

You need to create a capture session, and start it running. Once that's done you can add the layer from the capture session to your view:

- (void)setupCaptureSession
{
    NSError* error = nil;

    // Create the session
    _captureSession = [[AVCaptureSession alloc] init];    
    _captureSession.sessionPreset = AVCaptureSessionPresetMedium;
    AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

    [_captureSession addInput:input];
    AVCaptureVideoDataOutput* output = [[AVCaptureVideoDataOutput alloc] init];
    [_captureSession addOutput:output];

    // Configure your output.
   dispatch_queue_t queue = dispatch_queue_create("myCameraOutputQueue", NULL);
   //If you want to sebsequently use the data, then implement the delegate.
   [output setSampleBufferDelegate:self queue:queue]; 
}

Having done that, you can create a preview layer as follows:

_previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
[_captureSession startRunning];

And then add the preview layer to your view:

_myView.layer addSubLayer:_previewLayer];
Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • Hi, thanks for your quick reply! I've tried this, but the UIImageView is still not showing up the camera. I've replaced _myView with the UIImageView What to do now? – CyberK Jan 15 '13 at 12:34
  • _myView is the name of the view you want to add the camera to. Can you try setting that view with: _camera.previewLayer.frame = _myView.bounds; – Jasper Blues Jan 15 '13 at 12:36
  • When running [_captureSession startRunning], it provides me the view... But then I get an exception.. Any idea? – CyberK Jan 15 '13 at 12:48
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/22746/discussion-between-jasper-blues-and-cyberk) – Jasper Blues Jan 15 '13 at 12:49