camera preview later in macos in swift

Here's an example code snippet to create a live camera preview in macOS using AVFoundation in Swift:

main.swift
import Cocoa
import AVFoundation

class ViewController: NSViewController {

    var captureSession: AVCaptureSession!
    var previewLayer: AVCaptureVideoPreviewLayer!

    override func viewDidLoad() {
        super.viewDidLoad()

        setupCaptureSession()
        setupPreviewLayer()

        captureSession.startRunning()
    }

    func setupCaptureSession() {
        captureSession = AVCaptureSession()
        captureSession.sessionPreset = AVCaptureSession.Preset.photo

        let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .unspecified)
        guard
            let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice!),
            captureSession.canAddInput(videoDeviceInput)
        else { return }

        captureSession.addInput(videoDeviceInput)
    }

    func setupPreviewLayer() {
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        previewLayer.frame = view.bounds
        previewLayer.videoGravity = .resizeAspectFill
        view.layer?.addSublayer(previewLayer)
    }
}
1087 chars
38 lines

This code creates an AVCaptureSession and adds the built-in camera as a video input. It creates an AVCaptureVideoPreviewLayer to display the live camera feed in the view controller's view. Finally, it starts the capture session running.

gistlibby LogSnag