Take Photo Tutorial in iOS8 with Swift

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 built in iOS 8.1 and Xcode 6.1

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftTakePhotoTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

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".

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 an 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: UIButton) {
    imagePicker =  UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .Camera
    presentViewController(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(picker:didFinishMediaWithInfo)

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    imagePicker.dismissViewControllerAnimated(true, completion: nil)
    imageView.image = info[UIImagePickerControllerOriginalImage] 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 IOS8SwiftTakePhotoTutorial at the ioscreator repository on Github.