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.swift1763 chars59 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