2017-04-19 86 views
0

我使用Xamarin表单来制作QR码阅读器应用程序。我发现了ZXing的一个实现,但由于在async函数之外使用关键字await而导致运行我的代码时出现错误。然而,这个教程是这样做的,但是我不知道我在做错误来抛出错误。Xamarin Forms ZXing QR代码错误

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

回答

2

这是因为构造函数不能是异步的。只要将您的代码无效的方法,如:

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(); 
} 

另一种选择也许更好的(有一些调整,比如按钮cllick打开扫描仪页面)是OnAppearing方法创建扫描页面,但是当扫描完成Navigation.PopAsync()小心被称为并调用MainPage上的OnAppearing。所以在这种情况下,新的扫描页面将被推高。

1

此消息是因为您需要将async关键字包含在运行您的方法的外部方法中。您遇到的问题是您正在尝试在Page构造器上运行它,而这些不能是异步的。

你可以摆脱错误信息在页面移动无论是pushAsyncPage方法调用了构造函数的另一种方法,如OnAppearing和改变这支增加异步的签名,是这样的:

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

     if(isPageLoaded) 
      return; 

     isPageLoaded = true; 
     await pushAsyncPage(scanPage); 
    } 

或者将整块代码移动到相同的方法:

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    
    } 

这应该够了。

UPDATE

如下评论,使用此代码将需要具有可变知道该页面已加载,以防止再次展示了从扫描仪返回时,在斑马线上。

这就是我更喜欢在用户迭代(点击按钮,轻扫或任何其他手势)上打开扫描页面以避免这种循环的原因。

祝你好运。

+0

当他从扫描页面返回时,将调用MainPage上的OnAppearing并将新的scanPage推上。它的好场景? – puko

+0

@puko你是对的,没有接受。它需要验证用户是否正在从扫描页面返回。 – apineda