我尝试使用AVKit打开摄像机,在创建CameraView和AVCaptureVideoPreviewLayer对象时出现以下错误:Publishing changes from within view updates is not allowed, this will cause undefined behavior.
我知道可以通过添加DispatchQueue.main.async {}
来解决这个问题,但我不知道确切地把它放在哪里。
我正在创建CameraView,如下所示:
CameraView(size: geometry.size)
.environmentObject(cameraViewModel)
.ignoresSafeArea()
在里面,它看起来像:
struct CameraView: UIViewRepresentable {
@EnvironmentObject var cameraViewModel: CameraViewModel
var size: CGSize
func makeUIView(context: Context) -> UIView {
let view = UIView()
/* error occurs here */
cameraViewModel.capturePreview = AVCaptureVideoPreviewLayer(session: cameraViewModel.captureSession)
cameraViewModel.capturePreview.frame.size = size
cameraViewModel.capturePreview.videoGravity = .resizeAspectFill
view.layer.addSublayer(cameraViewModel.capturePreview)
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
最后,CameraViewModel保存capturePreview
,即:
@Published var capturePreview: AVCaptureVideoPreviewLayer!
1条答案
按热度按时间agxfikkp1#
我通过从
cameraViewModel
中删除@Published var capturePreview: AVCaptureVideoPreviewLayer!
并重新构造CameraView
来解决这个问题,如下所示: