'iOS swift ui show 2 view camera preview
I want to see the camera preview in both views, but I couldn't. Only 1 view displays an image. can you help me with this?
struct cameraview: View {
@StateObject var camera = cameramodel()
var body: some View{
VStack{
Camerapriview(camera: camera)
Camerapriview(camera: camera)
}.onAppear {
camera.check()
}
}
}
class cameramodel : ObservableObject {
@Published var istaken = false
@Published var session = AVCaptureSession()
@Published var output = AVCapturePhotoOutput()
@Published var priview : AVCaptureVideoPreviewLayer!
func check() {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized:
setup()
return
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { (status) in
if status {
self.setup()
}
}
default:
return
}
}
func setup(){
do{
self.session.commitConfiguration()
let device = AVCaptureDevice.default(.builtInDualWideCamera, for: .video, position: .back)
let input = try AVCaptureDeviceInput(device: device!)
if self.session.canAddInput(input){
self.session.addInput(input)
}
if self.session.canAddOutput(self.output){
self.session.addOutput(self.output)
}
}
catch{
print(error.localizedDescription)
}
}
}
struct Camerapriview: UIViewRepresentable{
var camera : cameramodel
func makeUIView(context: Context) -> some UIView {
let view = UIView(frame: UIScreen.main.bounds)
camera.priview = AVCaptureVideoPreviewLayer(session: camera.session)
camera.priview.videoGravity = .resize
camera.priview.frame = view.frame
view.layer.addSublayer(camera.priview)
camera.session.startRunning()
return view
}
func updateUIView(_ uiView: UIViewType, context: Context) {
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
