'Capturing a picture in SwiftUI by showing a sheet
Goal: To capture an image and provide it to a parent view via a binding to display it in the UI.
My code:
struct ImageShooter: UIViewControllerRepresentable {
@Binding var image: UIImage?
var captureSesssion = AVCaptureSession()
var output = AVCapturePhotoOutput()
func makeUIViewController(context: Context) -> UIViewController {
let camera = AVCaptureDevice.default(for: .video)
let input = try! AVCaptureDeviceInput(device: camera!)
captureSesssion.addInput(input)
captureSesssion.addOutput(output)
let preview = AVCaptureVideoPreviewLayer(session: captureSesssion)
preview.videoGravity = .resizeAspectFill
let vc = UIViewController()
vc.view.layer.addSublayer(preview)
preview.frame = vc.view.frame
return vc
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, AVCapturePhotoCaptureDelegate {
var parent: ImageShooter
init(_ parent: ImageShooter) {
self.parent = parent
}
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let imageData = photo.fileDataRepresentation() {
guard let image = UIImage(data: imageData) else { return }
self.parent.image = image
}
}
func photoOutput(_ output: AVCapturePhotoOutput, didFinishCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings, error: Error?) {
parent.output = output
parent.captureSesssion.stopRunning()
}
}
}
Problem: The screen remains black and no camera preview is shown. The sheet appears. The sheet can be dismissed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

