avfoundation Getting started with avfoundation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


This section provides an overview of what avfoundation is, and why a developer might want to use it.

It should also mention any large subjects within avfoundation, and link out to the related topics. Since the Documentation for avfoundation is new, you may need to create initial versions of those related topics.

Installation or Setup

A minimal setup for camera output preview (Swift 2, Swift 3)

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var session: AVCaptureSession?
    var cameraPreviewLayer: AVCaptureVideoPreviewLayer?

    override func viewDidLoad() {
        if let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session) {
            self.cameraPreviewLayer = cameraPreviewLayer

    func setupSession() {
        session = AVCaptureSession()
        //setup input
        let device =  AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        do {
            let input = try AVCaptureDeviceInput(device: device)
            if session?.canAddInput(input) == true {
        } catch {
            print("An error occured: \(error.localizedDescription)")

        //setup output
        let output = AVCaptureVideoDataOutput()
        output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable: kCVPixelFormatType_32BGRA]
        if session?.canAddOutput(output) == true {

    override func viewDidLayoutSubviews() {
        self.cameraPreviewLayer?.frame = self.view.layer.bounds

Got any avfoundation Question?