VNDocumentCameraViewController in Xamarin Forms freezes

225 views Asked by At

I would like to use the new VNDocumentCameraViewController from iOS 13 in my Xamarin Forms App with a custom renderer. It works, but sometimes after a few seconds the preview from the camera freezes and I have no chance to do anything on the view controller.

To reproduce the error, I've reduced my code to the following:

Custom view:

public sealed class Scanner : View
{
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App1"
             x:Class="App1.MainPage">
    <local:Scanner />
</ContentPage>

Custom renderer

[assembly: ExportRenderer(typeof(App1.Scanner), typeof(App1.iOS.ScannerRenderer))]

namespace App1.iOS
{
    public class ScannerRenderer : ViewRenderer<Scanner, UIView>
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Scanner> e)
        {
            base.OnElementChanged(e);

            if (this.Control == null)
            {
                VNDocumentCameraViewController scannerController = new VNDocumentCameraViewController();
                this.SetNativeControl(scannerController.View);
            }
        }
    }
}

It mostly occurs when moving the camera fast from left to right and back, but sometimes also without doing anything.

I didn't found anyone who tries to use the VNDocumentCameraViewController with Xamarin Forms. What I'm doing wrong? Or is there a bug?

1

There are 1 answers

0
Stephan Engelhardt On BEST ANSWER

I've found the solution...I struggled two days on it and now I found out, that the garbage collector did his f*** job and destroyed my scannerController after some time / called Dispose() of VNDocumentCameraViewController. If I changed it to a class member it worked:

Custom renderer

[assembly: ExportRenderer(typeof(App1.Scanner), typeof(App1.iOS.ScannerRenderer))]

namespace App1.iOS
{
    public class ScannerRenderer : ViewRenderer<Scanner, UIView>
    {
        private VNDocumentCameraViewController scannerController;
    
        protected override void OnElementChanged(ElementChangedEventArgs<Scanner> e)
        {
            base.OnElementChanged(e);

            if (this.Control == null)
            {
                this.scannerController = new VNDocumentCameraViewController();
                this.SetNativeControl(this.scannerController.View);
            }
        }
    }
}