Camera Feed is not working using AVFoundation

In this code, I aim to enable users to select an image from their phone gallery and display it with less opacity on top of the z-index. The selected image should appear on top of the user's phone camera feed, allowing them to see the canvas on which they are drawing as well as the low-opacity image. The app's purpose is to enable users to trace an image on the canvas while simultaneously seeing the camera feed.

CameraView.swift

import SwiftUI
import AVFoundation

struct CameraView: View {
    let selectedImage: UIImage
    
    var body: some View {
        ZStack {
            CameraPreview()
            Image(uiImage: selectedImage)
                .resizable()
                .aspectRatio(contentMode: .fill)
                .opacity(0.5) // Adjust the opacity as needed
                .edgesIgnoringSafeArea(.all)
        }
    }
}

struct CameraPreview: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        let cameraPreview = CameraPreviewView()
        return cameraPreview
    }

    func updateUIView(_ uiView: UIView, context: Context) {}
}

class CameraPreviewView: UIView {
    private let captureSession = AVCaptureSession()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCamera()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupCamera() {
        guard let backCamera = AVCaptureDevice.default(for: .video) else {
            print("Unable to access camera")
            return
        }
        
        do {
            let input = try AVCaptureDeviceInput(device: backCamera)
            if captureSession.canAddInput(input) {
                captureSession.addInput(input)
                
                let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                previewLayer.videoGravity = .resizeAspectFill
                previewLayer.frame = bounds
                layer.addSublayer(previewLayer)
                
                captureSession.startRunning()
            }
        } catch {
            print("Error setting up camera input:", error.localizedDescription)
        }
    }
}

Thanks for helping and your time.

I can see the green dot above the network bar so I am sure that the camera is being used but I am just unable to see the results. Please view the screen recording from my device for better understanding. https://rb.gy/m6v6ri

Instead of

layer.addSublayer(previewLayer)

write

self.layer = previewLayer 

in your CameraPreviewLayer.

Camera Feed is not working using AVFoundation
 
 
Q