Swift 3 - AVCapture custom camera view

Jeff Huang picture Jeff Huang · Oct 20, 2016 · Viewed 14.8k times · Source

I was following through this video to make a custom camera view. https://www.youtube.com/watch?v=w0O3ZGUS3pk

however due to iOS 10 and swift 3 changes many things weren't relevant anymore

the following is the code I got out after changing deprecated function to the new ones..however there is no error, but also not seeing a preview on the UIView

import UIKit
import AVFoundation

class ViewController: UIViewController, AVCapturePhotoCaptureDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    @IBOutlet weak var cameraView: UIView!
    var captureSession = AVCaptureSession();
    var sessionOutput = AVCapturePhotoOutput();
    var sessionOutputSetting = AVCapturePhotoSettings(format: [AVVideoCodecKey:AVVideoCodecJPEG]);
    var previewLayer = AVCaptureVideoPreviewLayer();

    override func viewWillAppear(_ animated: Bool) {
        let deviceDiscoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInDuoCamera, AVCaptureDeviceType.builtInTelephotoCamera,AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.unspecified)
        for device in (deviceDiscoverySession?.devices)! {
            if(device.position == AVCaptureDevicePosition.front){
                do{
                    let input = try AVCaptureDeviceInput(device: device)
                    if(captureSession.canAddInput(input)){
                        captureSession.addInput(input);

                        if(captureSession.canAddOutput(sessionOutput)){
                            captureSession.addOutput(sessionOutput);
                            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
                            previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
                            previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.portrait;
                            cameraView.layer.addSublayer(previewLayer);
                        }
                    }
                }
                catch{
                    print("exception!");
                }
            }
        }
    }

Answer

Rhythmic Fistman picture Rhythmic Fistman · Oct 21, 2016

You've forgotten to start your session:

captureSession.startRunning()

and set the frame for your previewLayer:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    previewLayer.frame = cameraView.bounds
}

p.s. Once you've added your session inputs and outputs, you should break out of that loop.