Take Photos With the Camera

In this tutorial we are going to use the camera of the iphone to take picture and display the photo in our app. This tutorial is made with Xcode 4.5 and the build target is iOS6.

Update: Jan 21, 2015. The rewritten version in Swift for iOS 8.1 and Xcode 6.1 is available here.

Create a new Project, select the Single View Template and name the app CameraApp. Deselect the use storyboard and select the use automatic reference counting checkbox. Build for the iPhone device.

To show and use the default camera view we must set our viewcontroller as a UIImagePickerControllerDelegate and UINavigationControllerDelegate. Change the @interface line in ViewController.m to

@interface iOSViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

We need a imageview to display the taken photo and a button to take the photo. Let's create the needed properties


@property (nonatomic, strong) IBOutlet UIImageView *imageView;
@property (nonatomic, strong) IBOutlet UIButton *takePhotoButton;

To take the photo we need to declare a IBAction.

- (IBAction)getPhoto:(id)sender;

Go to ViewController.xib. Drag a Image View and a Round Rect Button onto the View. Select the Image View and go to the attributes inspector. Select Aspect Fit mode. The view should look like this

Ctrl+Drag from the File's Owner to the ImageView and the button to connect the outlets. Ctrl+Drag from the Take Photo button to the File's Owner and select the takePhoto Action.

Now we will fill the TakePhoto method in ViewController.m. Initialize a imagepickercontroller and set the delegate to the view controller.

- (IBAction)getPhoto:(id)sender 
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;

Set the source type to Camera, it is also possible to set the source type to video.

picker.sourceType = UIImagePickerControllerSourceTypeCamera;

Present the view controller, this will take you to the Camera screen.

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

When the photo is taken, you can choose to use this photo, when this is done we need to take back to our initial view, where the picture will be displayed. Part of the UIImagePickerControllerDelegate is the imagePickerController:didFinishPickingMediaWithInfo method,

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
[picker dismissViewControllerAnimated:YES completion:NULL];
self.imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

Build and Run this project on a iOS device, take a Photo and it will be displayed