Peculiarities of UIImagePickerController

Disclaimer. The author is not liable for any butthurt this article may cause.
If you are butthurted reading this article - you are careless coder.


UIImagePickerController is often used in iOS applications. It manages customizable, system-supplied user interfaces for taking pictures and movies on supported devices, and for choosing saved images and movies for use in your app.

The Problem

Because a media source may not be present or may be unavailable, devices may not always support all source types. For example, if you attempt to pick an image from the user’s library and the library is empty, using UIImagePickerController calling it with presentViewController:animated:completion: will result you in a crash. Similarly, you'll get your crash if the camera is already in use or unavailable on this device (simulator, broken device).

Careless Coder's Approach

Careless coders:

  • assume that all iOS devices have camera;
  • do not think how UIImagePickerController will work if the library is empty;
  • and what's the most irritating think that "it is iOS simulator's problem that it does not have a camera. My code is good..."

A Word of Wisdom Comes

Sons, when you see that your bullshit crashes or know the circumstances when it crashes get off your ass and fuckin' Google what your savvy colleagues say on this. In 99% of the cases it helps1.

And for the most advanced rest of you there is one more advice: read the references for the API you're using. It usually covers most of the special situations.
In the case of UIImagePickerController Apple's reference clearly states the correct workflow.
Hint: here. Starting from the third paragraph.

The Solution

Before attempting to use an UIImagePickerController object to pick an image, you must call + isSourceTypeAvailable: method to ensure that the desired source type is available.

Snippet for The Photo Library
    if (NO == [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIAlertView *noCameraAlert = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Seems like you have no photos in your library" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

        //shows above alert if there's no camera
        [noCameraAlert show];

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:picker animated:YES completion:NULL];

Hint: the same snippet could be applied to the case when there is no camera available. Guess how!


The good code never crashes. It handles problematic cases elegantly.
Writing the good code is a work full of tension and thinking.
Do not stay careless!

Good coding!

  1. Note that it may not help if you're preparing to invade Mars or dealing with the antimatter.