简体   繁体   中英

Xamarin Forms ZXing QR Code Error

I am using Xamarin forms to make a QR code reader app. I have found an implementation by ZXing but I am getting an error when running my code due to using the await keyword outside of an async function. The tutorial does it this way however, but I don't know what I am doing wrong to throw the error.

using Xamarin.Forms;
using ZXing.Net.Mobile.Forms;

namespace App3
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            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
        }
    }  
}

The error is:

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'

It is because constructor cant be asynchronous. Just move your code to void method like:

private async void InitializeScanner()
{
   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 pushAsyncPage(scanPage); 
}

public MainPage()
{
   InitializeComponent();
   InitializeScanner();
}

Another option maybe better (with some adjustments eg opening scanner page on button cllick) is create scan page in OnAppearing method, but be careful when scan is completed Navigation.PopAsync() is called and OnAppearing on your MainPage is called. So in that case new scan page will be pushed up.

This message is because you need to include the async keyword to the outer method that is running your method. The problem you have is that you are trying to run it at the Page constructor and these cannot be async.

You can get rid of the error messages moving either the pushAsyncPage method call out of the constructor to another method in the Page like the OnAppearing and change the signature of this adding async, something like:

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

        if(isPageLoaded)
            return;

        isPageLoaded = true;
        await pushAsyncPage(scanPage);
    }

Or moving the whole block of code to the same method:

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

        if(isPageLoaded)
            return;

        isPageLoaded = true;

        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 pushAsyncPage(scanPage); // Here is the error            
    }

This should be enough.

UPDATE

As commented below, using this code will require having a variable to know if the page is already loaded to prevent the ZXing page showing again when returning from the scanner.

This is the reason I do prefer opening the scanning page on an user iteration (tap of a button, swipe or any other gesture) to prevent loops like this.

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM