Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - AVCapture custom camera view

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!");
                }
            }
        }
    }
like image 698
Jeff Huang Avatar asked Oct 20 '16 15:10

Jeff Huang


1 Answers

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.

like image 84
Rhythmic Fistman Avatar answered Oct 22 '22 04:10

Rhythmic Fistman