Skip to main content
Language

Present Camera using SwiftUI

Since we are using UIKit in our example application we need to use an UIHostingController to present a SwiftUI View. The PhotoCameraSwiftUIView defined below wraps the actual Camera view to coordinate its dismissal with the presenting UIViewController. This process is not necessary for a pure SwiftUI application. You would use the Camera view directly.

Configure and create the view#

In order to record and access photos in the camera roll the NSCameraUsageDescription and NSPhotoLibraryUsageDescription key need to be present in your Info.plist file.

The custom PhotoCameraSwiftUIView acts as the ContentView of a pure SwiftUI application.

First, we create several instance variables; the photo to reference recorded or selected photos, a boolean variable pesdkPresented to indicate whether the editor view should be presented and a PhotoEditModel which holds the edit state of the camera view i.e. filters that have been applied.

Next, we create a configuration object setting allowedRecordingModes to [.photo], since we only want to enable recording and selecting photos not videos. By default, the camera view controller does not show a cancel button so that it can be embedded into any other view controller. But since it is presented modally in this example, a cancel button should be visible.

Refer to the configuration guide for a detailed explanation of how to configure the editor.

Next, we initialize the Camera with the configuration object and use the fullScreenCover in combination with the onChange modifier to edit the photo with the PhotoEditor.

Handling events#

Using the onDidSave modifier allows us to register an event handler that is invoked when a user successfully recorded or selected a photo. The result argument passed to the closure is of type CameraResult and contains the data of the photo and a PhotoEditModel allowing us to pass on the applied filters to the editor.

Likewise, if the user taps the cancel button we dismiss the camera in this example.

Next Steps#