Skip to main content

Select a photo with UIImagePickerController

To select a photo from your library we can use the built in UIImagePickerController.

This is simple to use and allows you to select and use an image already saved to your device.

To start with we create a new UIImagePickerController class with:

let imagePickerController = UIImagePickerController()

We then assign its delegate and set its sourceType which below we set to PhotoLibrary so we can access our photos.

Finally we present the newly created controller using presentViewController.

The code above is wrapped in a button press action but is does not need to be.

To use the imagePickerController we need to implement the delegate UINavigationControllerDelegate and the UIImagePickerControllerDelegate.

We are going to need to implement a couple of delegate methods from the UIImagePickerControllerDelegate.

The first is imagePickerController:didFinishPickingMediaWithInfo

This method is used to select the image and close the controller. Here we use the image of imageSelected and assign it to the UIImageView photoImageView to display it.

We then close the UIImagePickerViewController with dismissViewController.

The second is imagePickerControllerDidCancel. This handles cancelling the imagePickerController.

You can view an example project of this code here

Please follow and like us: