如何正确等待我的条形码扫描

时间:2017-10-02 14:31:22

标签: c# xamarin.forms async-await zxing.net

目前我正在努力等待阅读我的QR码:

private async Task<string> ScanQRCode()
    {
        try
        {
            var options = new MobileBarcodeScanningOptions
            {
                AutoRotate = false,
                UseFrontCameraIfAvailable = false,
                TryHarder = true,
                DelayBetweenContinuousScans = 1
            };
            var scanPage = new ZXingScannerPage(options)
            {
                DefaultOverlayTopText = "Align the barcode within the frame",
                DefaultOverlayBottomText = string.Empty,
                DefaultOverlayShowFlashButton = true
            };

            string barcodestring = string.Empty;

            // Navigate to our scanner page
            Device.BeginInvokeOnMainThread(async () =>
            {
                await _navigation.PushModalAsync(scanPage);
            });

            scanPage.OnScanResult += (result) =>
            {
                if (result.Text.IsValidJson<DeviceSetup>())
                {
                    // Stop scanning
                    scanPage.IsScanning = false;

                    // Pop the page and show the result
                    Device.BeginInvokeOnMainThread(async () =>
                    {
                        await _navigation.PopModalAsync(true);
                    });
                    barcodestring = result.Text;
                }
            };

            return barcodestring;
        }
        catch (System.Exception ex)
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await _navigation.PopModalAsync(true);
                await _page.DisplayAlert("Error", ex.Message, "OK");
            });
            return "Error";
        }
    }

调用方法继续执行,不等待QR结果..

为什么?

1 个答案:

答案 0 :(得分:1)

我认为你的问题是你的

await _navigation.PushModalAsync(scanPage)
扫描页面可视化时

结束。所以你的

return barcodestring;

我认为返回总是一个空字符串。

您应该使用MessagingCenter

            if (result.Text.IsValidJson<DeviceSetup>())
            {
                // Stop scanning
                scanPage.IsScanning = false;

                // Pop the page and show the result
                Device.BeginInvokeOnMainThread(async () =>
                {
                    await _navigation.PopModalAsync(true);
                });

                // Here send a message
                MessagingCenter.Send<MyPage, string>(this, "BarcodeRead", result.Text);
                //barcodestring = result.Text;
            }

你的MyPage应该有(在OnAppearing中)像

这样的东西
MessagingCenter.Subscribe<MyPage, string> (this, "BarcodeRead", (sender, arg) => {
    // arg should have your barcode...
});

我创建了一个小型演示TestZXing。这是https://github.com/Redth/ZXing.Net.Mobile

上重现的演示