Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Camera in iOS app Tutorial

Tags:

ios

camera

I was wondering if anyone was willing to share how to put a Camera feature into an iOS app, or if anyone knew of a simple tutorial. NOT one with any buttons, just showing on the screen what the camera is seeing. I tried Apple's Documentation, but it was too complex for my needs.

Thank you so much!

EDIT: Any simple tutorial will do fine. Like I said, I don't need anything else, besides it to display what the camera is seeing.

like image 777
Branch Avatar asked Dec 19 '13 23:12

Branch


1 Answers

I don't know about a simple tutorial but adding a view that shows what the camera sees is super easy.

First:

Add a UIView to your interface builder that will be where the camera will be shown.

Second:

Add the AVFoundation framework to your project, and add its import to your ViewController .m file.

#import <AVFoundation/AVFoundation.h>

Third:

Add these 2 variables to your interface variable declarations

AVCaptureVideoPreviewLayer *_previewLayer;
AVCaptureSession *_captureSession;

Fourth:

Add this code to your viewDidLoad. (The explanation of what it does is commented)

//-- Setup Capture Session.
_captureSession = [[AVCaptureSession alloc] init];

//-- Creata a video device and input from that Device.  Add the input to the capture session.
AVCaptureDevice * videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if(videoDevice == nil)
    assert(0);

//-- Add the device to the session.
NSError *error;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice
                                                                    error:&error];
if(error)
    assert(0);

[_captureSession addInput:input];

//-- Configure the preview layer
_previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
_previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

[_previewLayer setFrame:CGRectMake(0, 0,
                                   self.cameraPreviewView.frame.size.width,
                                   self.cameraPreviewView.frame.size.height)];

//-- Add the layer to the view that should display the camera input
[self.cameraPreviewView.layer addSublayer:_previewLayer];

//-- Start the camera
[_captureSession startRunning];

Notes:

  1. The asserts will make the program exit in places where a camera is not available.

  2. This only shows "The preview" of what the camera sees, if you want to manipulate the input, or take a picture or record the video you need to configure additional things like the SessionPreset and add the corresponding capture delegates. But in that case you should follow a proper tutorial or read the documentation.

like image 182
Pochi Avatar answered Oct 17 '22 19:10

Pochi