liv a liv a - 3 months ago 32
Objective-C Question

open the camera in my own uiview without opening the camera application

My Iphone application uses the camera, I have the following code:

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = NO;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;

[self presentViewController:picker animated:YES completion:NULL];

I wish that the camera application will not open and instead i'll have the camera feed in my own uiview or uiimageview is that possible?

I've tried this line of code instead of
[self presentViewController:picker animated:YES completion:NULL];

[self.view addSubview:picker];

this results in an exception
[UIImagePickerController superview]: unrecognized selector sent to instance

I found this great tutorial including a code sample and a download project


You can achieve this using the following code:

#import <AVFoundation/AVFoundation.h>

AVCaptureSession *session = [[AVCaptureSession alloc] init];
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (videoDevice)
    NSError *error;
    AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
    if (!error)
        if ([session canAddInput:videoInput])
            [session addInput:videoInput];
            AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
            previewLayer.frame = self.view.bounds;
            [self.view.layer addSublayer:previewLayer];
            [session startRunning];