Search code examples
c#xamarinxamarin.formsasync-awaitzxing

Xamarin PushAsync method not supported


I've read this thread and a few others about similar errors, but unfortunately I still don't understand how to fix my problem.

I have a method that should open a ZXScannerPage so that I can read QR codes

protected override async void OnAppearing()
    {
        base.OnAppearing();

        var scanPage = new ZXingScannerPage();
        scanPage.OnScanResult += (result) => {
            // Stop scanning
            scanPage.IsScanning = false;

            // Pop the page and show the result
            Device.BeginInvokeOnMainThread(() => {
                Navigation.PopAsync();
                DisplayAlert("Scanned Barcode", result.Text, "OK");
            });
        };

        // Navigate to our scanner page
        await Navigation.PushAsync(scanPage); // Here is the error            
    }

I need to use this function before my await Navigation.PushAsync(scanPage); call

MainPage = new NavigationPage(<Something goes here>);

But I am unsure where this should go, and what arguments I should feed it


Solution

  • PushAsync method is not supported because MainPage of the app is not NavigationPage.

    Create page in which overrides OnAppearing method. In this method use your code.

    When application started in App.xaml.cs or App.cs depends on project type, call in constructor

    MainPage = new NavigationPage(new YourPage());
    

    This will call OnAppearing method in your page and your code push the scanner page up.

    EDIT U can use your scannerPage like

    var scanPage = new ZXingScannerPage();
    scanPage.OnScanResult += (result) => {
                // Stop scanning
                scanPage.IsScanning = false;
    
                // Pop the page and show the result
                Device.BeginInvokeOnMainThread(() => {
                    Navigation.PopAsync();
                    DisplayAlert("Scanned Barcode", result.Text, "OK");
                });
            };
    MainPage = new NavigationPage(scanPage);
    

    In this case after scan is completed Navigation.PopAsync() will not work because in navigation stack is only one page (except NavigationPage).