Take Photo iOS Tutorial

Apple provides the UIImagePickerController which is an user interface to take photos using the built-in camera of an iOS device. In this tutorial we will take a photo and display it in an Image View. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSTakePhotoTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and drag an Image View from the Object Library to the main view. Go to the Size inspector and enter the following values.

Drag a Button from the Object Library to the main view and place it below the Image View. Give the button a title of "Take Photo". The Storyboard will look like this.

To use the camera inside the app, permission must be granted by the user. Go to the info.plist and add the following row

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Image to the ViewController class and create the following Outlet.

Ctrl and drag from the Button to the ViewController class and create the following Action

Go to the ViewController.swift file and create the following property

var imagePicker: UIImagePickerController!

Change the class declaration line to.

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

The ViewController now needs to conform to the UINavigationControllerDelegate and UIImagePickerControllerDelegate protocol. Next, implement the takePhoto IBAction method

@IBAction func takePhoto(_ sender: Any) {
    imagePicker =  UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .camera

    present(imagePicker, animated: true, completion: nil)

The Image Picker Controller is initialized with a source type of Camera and it will be presented. Next, implement the UIImagePickerController delegate method imagePickerController(_:didFinishMediaWithInfo:)

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        imagePicker.dismiss(animated: true, completion: nil)
        imageView.image = info[.originalImage] as? UIImage

The Image Controller is dismissed and the photo is assigned to the Image View. The info parameter is a dictionary containing the original image. Build and Run the project and grant access to the built-in camera.

Select "Take Photo" and take a photo. Choose "Use Photo" to display the photo inside the Image View.

You can download the source code of the IOSTakePhotoTutorial at the ioscreator repository on Github.