[Xamarin] Scanning QRCode in a Xamarin.Forms application

September 29th, 2014 | Posted by Tom in .NET | Article | Xamarin | Read: 16,027

Scanning QRCodes (or barcodes) in a Xamarin.Forms application is really easy thanks to a well-know project ZXing, that has been ported to Xamarin (and for all the devices: iOS, Android and Windows Phone).

 

To implement the feature, first add a reference to the ZXing component to your projects. Then, as always, we need to find a way to communicate between the Forms project (that contains the logic) and the various UI projects. To solve this, we’ll used the DependencyService to register an interface and create the various implementations.

The interface is pretty simple:

public interface IQrCodeScanningService
{
    Task<string> ScanAsync();
}

And here is the implementation for the Windows Phone project:

public class QrCodeScanningService : IQrCodeScanningService
{
    public async Task<string> ScanAsync()
    {
        var scanner = new ZXing.Mobile.MobileBarcodeScanner(App.RootFrame.Dispatcher);
        var scanResults = await scanner.Scan();

        return scanResults.Text;
    }
}

And now, let’s take a look to the implementation for the Android project (of course, it’s also possible to create an iOS implementation):

public class QrCodeScanningService : IQrCodeScanningService
{
    public async Task<string> ScanAsync()
    {
        var scanner = new ZXing.Mobile.MobileBarcodeScanner(Application.Context);
        var scanResults = await scanner.Scan();

        return scanResults.Text;
    }
}

As you can see, each version is particular (the constructor of the MobileBarcodeScanner takes a different parameters, according to the platform).

For each implementation, don’t forget to add the Dependency attribute so the DependencyService can register the interface and the implementation:

// Windows Phone
[assembly: Dependency (typeof(QrCodeScanningService))]
namespace QrCodeScanningWithXamarin.WinPhone.Helpers

// Android
[assembly: Dependency(typeof(QrCodeScanningService))]
namespace QrCodeScanningWithXamarin.Droid.Helpers

And now, in the Forms project (Shared or portable), we can use the DependencyService to retrieve the instance of the class that implement our interface:

var scanButton = new Button
{
    Text = "Launch scan"
};
scanButton.Clicked += async (sender, args) =>
{
    var url = await DependencyService.Get<IQrCodeScanningService>().ScanAsync();

    Device.OpenUri(new Uri(url));
};

Launch your application and click on the button to display the overlay allowing the user to scan a QRCode or Barcode. Once the view appears on the screen, click on it and, after the autofocus is performed, the scan is done and the results are returned so you can use them (display them, launch the URL, etc.)

 

Happy coding!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Add Comment Register



Leave a Reply