show camera on swiftui in swift

To show the camera on a SwiftUI view, you can use the UIImagePickerController from AVFoundation framework. Here is some sample code on how to present the camera on a SwiftUI view:

main.swift
import SwiftUI
import AVFoundation

struct CameraView: UIViewControllerRepresentable {
    
    @Environment(\.presentationMode) var presentationMode
    
    func makeUIViewController(context: Context) -> UIImagePickerController {
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = .camera
        imagePicker.delegate = context.coordinator
        return imagePicker
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
        // No update needed
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(presentationMode: presentationMode)
    }
    
    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        
        let presentationMode: Binding<PresentationMode>
        
        init(presentationMode: Binding<PresentationMode>) {
            self.presentationMode = presentationMode
        }
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let image = info[.originalImage] as? UIImage {
                // Handle captured image
            }
            
            presentationMode.wrappedValue.dismiss()
        }
        
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            presentationMode.wrappedValue.dismiss()
        }
    }
}

struct ContentView: View {
    @State private var showCamera = false
    
    var body: some View {
        Button(action: {
            showCamera = true
        }) {
            Text("Take Photo")
        }
        .sheet(isPresented: $showCamera) {
            CameraView()
        }
    }
}
1763 chars
59 lines

This code creates a CameraView which implements the UIViewControllerRepresentable protocol. The makeUIViewController function returns an instance of UIImagePickerController with .camera as the sourceType. The updateUIViewController function is empty since we don't need to update the controller once it is created.

The CameraView also has a Coordinator class which implements the UINavigationControllerDelegate and UIImagePickerControllerDelegate. This class takes care of dismissing the UIImagePickerController once an image is selected or the cancel button is tapped.

In the ContentView, a Button is used to present the camera as a sheet using the sheet modifier. When the button is tapped, the showCamera state is set to true which presents the CameraView as a sheet.

gistlibby LogSnag