How to select a UIImage from the camera roll (and use it)

The UIImagePickerController can help us do this with ease.

In this example we’ll instantiate it, then we tell it what kind of image we want returned (we’re using an edited version here, but we could just as well return the original, or start using a camera). Next we present a modal view controller where the actual image selection takes place:

    // let's grab a picture from the media library
    UIImagePickerController *myPicker = [[UIImagePickerController alloc]init];
    myPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    myPicker.allowsEditing = YES;
    myPicker.delegate = self;
    
    // now we present the picker
    [self presentModalViewController:myPicker animated:YES];

For this to work you need to conform to the UIImagePickerControllerDelegate protocol, as well as the UINavigationControllerDelegate (the latter does not need any methods – it’s just so that the warning to myPicker.delegate = self goes away really).

The two methods we need from the first protocol are to deal with a selection and a cancellation. In this example I’m displaying the returned image in a UIImageView:

// an image is selected
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissModalViewControllerAnimated:YES];
    UIImage *chosenImage = [info objectForKey:UIImagePickerControllerEditedImage];
    self.myPicture.image = chosenImage;
}

// user hits cancel
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}




Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.