Taking and sharing photos is an important feature of many apps. Using the UIImagePickerViewController is a simple and easy way of enabling your user to either take a new photo or get an existing one from the user’s photo library.


First of all, we want to start a new single application template project. We want to set up our main view controller, with the main image view, camera and library button.

Screen Shot 2018-02-04 at 6.10.30 PM.png

Then we want to add an important string to our info.plist. We need to add an NSCameraUsageDescription so that we can access the devices’ camera. This is a small sentence that describes to the user why your app requires access to the camera. My sentence is only an example, you can replace it with any description you’d like.

Screen Shot 2018-02-04 at 6.04.35 PM

Then we have to implement the code within our UIViewController to handle the button presses, present the UIImagePickerViewController and then handle the UIImagePickerViewControllerDelegate.

import UIKit
// MARK: ImagePickerViewController
class ImagePickerViewController: UIViewController {
// MARK: Outlets
@IBOutlet var cameraButton: UIButton!
@IBOutlet var libraryButton: UIButton!
@IBOutlet var mainImageView: UIImageView!
// MARK: IBAction Methods
@IBAction func camera(sender: Any?) {
presentUIImagePicker(sourceType: .camera)
@IBAction func library(sender: Any?) {
presentUIImagePicker(sourceType: .photoLibrary)
// MARK: Helper Methods
private func presentUIImagePicker(sourceType: UIImagePickerControllerSourceType) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = sourceType
present(picker, animated: true, completion: nil)
// MARK: UIImagePickerControllerDelegate and UINavigationControllerDelegate
extension ImagePickerViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
guard let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
dismiss(animated: true, completion: nil)
mainImageView.image = chosenImage
dismiss(animated: true, completion: nil)
@objc func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)

Here is the full source code for the project:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.