When using VisionKit's VNDocumentCameraViewController for scanning documents the camera hangs after some seconds. The scan is implemented in a ViewController, which is used in SwiftUI.
The implementation of a DocumentScannerViewController:
import UIKit
import VisionKit
import SwiftUI
final class DocumentScannerViewController: UIViewController, VNDocumentCameraViewControllerDelegate, UIViewControllerRepresentable {
public typealias UIViewControllerType = DocumentScannerViewController
public func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentScannerViewController>) -> DocumentScannerViewController {
return DocumentScannerViewController()
}
public func updateUIViewController(_ uiViewController: DocumentScannerViewController, context: UIViewControllerRepresentableContext<DocumentScannerViewController>) {
}
override func viewDidLoad() {
super.viewDidLoad()
let scannerViewController = VNDocumentCameraViewController()
scannerViewController.delegate = self as VNDocumentCameraViewControllerDelegate
view.addSubview(scannerViewController.view)
}
func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {
}
func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {
}
func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFailWithError error: Error) {
}
}
And the implementation of the ContentView:
import SwiftUI
struct ContentView: View {
var body: some View {
DocumentScannerViewController()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The document scan camera launches and works for a short period of time. Then camera just stops moving.
Any idea what causes this behavior?
Apple does provide a way to use
ViewControllers
inside SwiftUI view withUIViewControllerRepresentable
which you have to implement this way.First declare your View as follows:
You can now call your view this way: