Skip to content

Instantly share code, notes, and snippets.

@hassanvfx
Created January 4, 2023 05:24
Show Gist options
  • Save hassanvfx/4d6b038555c46a480a7342f99b4ed125 to your computer and use it in GitHub Desktop.
Save hassanvfx/4d6b038555c46a480a7342f99b4ed125 to your computer and use it in GitHub Desktop.
Basic Camera Display / Buffer Analysis in SwiftUI
import SwiftUI
import AVFoundation
struct CameraView: View {
// Set up the AVCaptureSession and AVCaptureVideoPreviewLayer
let captureSession = AVCaptureSession()
let previewLayer = AVCaptureVideoPreviewLayer()
let cameraDelegate = CameraDelegate()
var body: some View {
// Use a GeometryReader to get the size of the view
GeometryReader { geometry in
// Set up the camera preview
ZStack {
PreviewLayerView(previewLayer: self.previewLayer)
.id("\(geometry.size.width)x\(geometry.size.height)")
}
.onAppear {
self.previewLayer.frame = geometry.frame(in: .global)
self.previewLayer.bounds = geometry.frame(in: .global)
self.previewLayer.session = captureSession
let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self.cameraDelegate as AVCaptureVideoDataOutputSampleBufferDelegate, queue: DispatchQueue(label: "sample buffer delegate", attributes: []))
guard let device = AVCaptureDevice.default(for: .video) else {
fatalError()
}
if let input = try? AVCaptureDeviceInput(device: device) {
captureSession.addInput(input)
} else {
print("camera input error")
}
if captureSession.canAddOutput(videoOutput) {
captureSession.addOutput(videoOutput)
}
self.captureSession.startRunning()
}
// Stop the capture session when the view disappears
.onDisappear {
self.captureSession.stopRunning()
}
}
}
}
struct PreviewLayerView: UIViewRepresentable {
let previewLayer: AVCaptureVideoPreviewLayer
func makeUIView(context: Context) -> UIView {
let view = UIView(frame: .zero)
view.layer.addSublayer(previewLayer)
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
previewLayer.frame = uiView.bounds
}
}
class CameraDelegate: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// Analyze the frame here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment