---
title: "#102: Building a Camera (Part 2) 📷"
url: https://littlebitesofcocoa.com/102-building-a-camera-part-2
author: Jake Marsh
published: 2015-10-13
topics: ["Images","Media","AVFoundation"]
description: "In Bite #101 we started working on a custom camera view controller. Today we'll complete it by adding a way for users to capture a photo and do something..."
---

# #102: Building a Camera (Part 2) 📷

By Jake Marsh, October 13, 2015. HTML: https://littlebitesofcocoa.com/102-building-a-camera-part-2

In [Bite #101](https://littlebitesofcocoa.com/101) we started working on a custom _camera view controller_.

Today we'll complete it by adding a way for users to capture a photo and do something with it. We'll start by making it easy to use. We'll make the whole screen a capture button by adding a **tap gesture recognizer** to our **view**:

``` swift
let tapGR = UITapGestureRecognizer(target: self, action: "capturePhoto:")
tapGR.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGR)
```

Next, we want to ask our **output** to capture a still image. Before we can, we'll need an **AVCaptureConnection**.

**Connections** were already implicitly created for us by our **session**. They represent the <i>conceptual</i> pipes that move data between **inputs** and **outputs**.

We grab a **connection** and use it to ask our **output** to capture a still image, asynchronously:

``` swift
func capturePhoto(tapGR: UITapGestureRecognizer) {
  guard let connection = output.connectionWithMediaType(AVMediaTypeVideo) else { return }
  connection.videoOrientation = .Portrait

  output.captureStillImageAsynchronouslyFromConnection(connection) { (sampleBuffer, error) in
    guard sampleBuffer != nil && error == nil else { return }

    let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
    guard let image = UIImage(data: imageData) else { return }

    self.presentActivityVCForImage(image)
  }
}
```

In the closure, we'll do a safety check then convert the **CMSampleBuffer** we've been given into an **NSData** then a **UIImage**.

Lastly, we'll use **UIActivityViewController** (covered in [Bite #71](https://littlebitesofcocoa.com/71)) to allow the user to do something with their new photo.

<img src='https://media.littlebitesofcocoa.com/bite-assets/102-building-a-camera-part-2-final-product.png' style='max-width: 205px;' />

**Download the project** we built in [Bites #101](https://littlebitesofcocoa.com/101) & [#102](https://littlebitesofcocoa.com/102) at [j.mp/bite102](http://j.mp/bite102)
