Buddybuild is a CI, CD and user feedback platform built for mobile development teams - sign up for free and start building better apps!


#83: UIImagePickerController Basics 📷


UIImagePickerController has been part of iOS since it's first release and it's evolved quite a bit over the years. Let's take a look at what it can do:

  • Capture images and videos
  • Choose images and videos from the Photos library
  • Crop images after choosing/capturing
  • Trim videos after choosing/capturing

Whew! That's quite a bit of functionality packed into this one class.

We can't cover all of that in this Bite, instead let's look at a simple example use case. We'll be letting our users take a photo, crop it, and then show how to access it for use in our app.

The first step is to find out the device we're running on has a camera, can take photos. Then we'll configure the UIImagePickerController and present it.

let types = UIImagePickerController.availableMediaTypesForSourceType(.Camera)!
let canTakePhotos = types.contains(kUTTypeImage as String)

if UIImagePickerController.isSourceTypeAvailable(.Camera) && canTakePhotos {
  let ipc = UIImagePickerController()

  ipc.sourceType = .Camera
  ipc.mediaTypes = [kUTTypeImage as String]
  ipc.allowsEditing = true
  ipc.delegate = self

  presentViewController(ipc, animated: true, completion: nil)

Then we'll add a function from UIImagePickerControllerDelegate where we'll get a userInfo dictionary. We'll use the values inside to extract the captured image in either it's original or cropped form. We can also access a few other details, like the cropped rect as a CGRect or the image's metadata as a dictionary.

Note that we'll need to declare conformance to the UINavigationControllerDelegate protocol since UIImagePickerController is actually a subclass of UINavigationController under the hood.

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
  func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) {
    let uncroppedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
    let croppedImage = info[UIImagePickerControllerEditedImage] as? UIImage
    let cropRect = info[UIImagePickerControllerCropRect]!.CGRectValue

    picker.dismissViewControllerAnimated(true, completion: nil)

  func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    picker.dismissViewControllerAnimated(true, completion: nil)