Jan Sanchez

Using UIImagePickerController

Have you ever found the need in your app to let the user take a Picture or choose one from the Camera Roll? Follow and find how easy is to add this feature to your app.

The iOS SDK provides a native controller that handles the hard bits for you. This controller is UIImagePickerController.

1
2
3
4
5
6
UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
pickerController.delegate = self;
[self presentViewController:imagePickerController
                   animated:YES
                 completion:NULL];

In this particular example it will bring the camera. There are other options as well.

1
2
3
4
5
6
// This will bring the Camera
pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
// Option for showing the photo library
pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// This will just show the photos / videos view
pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;

Note that the last two options require users to allow the app to access their photos / videos.

Don’t forget to check if the source type is available:

1
2
3
4
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  // Set sourceType to UIImagePickerControllerSourceTypeCamera
  // and present controller
}

If you do not care about movies, just still images we can set the media typpe to kUTTypeImage.

1
2
3
#import <MobileCoreServices/MobileCoreServices.h>
// Don't forget to add MobileCoreServices.framework to the project
pickerController.mediaTypes = @[(NSString *)kUTTypeImage];

This class also supports the ability to let users crop and scale pictures. This is very useful if want to get square pics, for instance to update a social profile picture.

1
pickerController.allowsEditing = YES;

To get the actual image that users picked we implement one of UIImagePickerControllerDelegate methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
  [self dismissViewControllerAnimated:YES completion:NULL];
  // UIImagePickerControllerEditedImage is useful if you allowed
  // editing of images
  UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
  if (image == nil)
    image = [info objectForKey:UIImagePickerControllerOriginalImage];

  // Do something with the image

}

As you can see, UIImagePickerController is quite easy to implement and it has lots of options that you can make use of. It also allows you to set a custom overlay and define your own camera buttons.

This sample code can be found in my GitHub repo.