USING IRONQR

How to use .NET MAUI For QR Code scanner

Published January 13, 2025
Share:

Introduction

With the rise of mobile applications leveraging QR Codes for quick information retrieval, the need for an efficient and easy-to-integrate QR Code scanner as well as a .NET MAUI Barcode scanner to scan Barcodes is growing. .NET MAUI (Multi-platform App UI), Microsoft's cross-platform framework, provides a unified environment for building applications across iOS, Android, macOS, and Windows. When scanning QR Codes in a .NET MAUI application, developers need an intuitive and powerful library to manage the process.

IronQR is a popular library that allows developers to generate and decode QR codes quickly, accurately, and reliably. This article will walk you through integrating IronQR with .NET MAUI to build a QR/ Barcode scanner that can work seamlessly across multiple platforms.

How to implement QR Barcode Scanning using IronQR

  1. Create .NET MAUI Project.

  2. Install the IronQR NuGet package.

  3. Set up permissions for camera and file storage.

  4. Implementing the QR Code Scanner.

Introduction to IronQR for .NET MAUI Mobile Apps

IronQR is a powerful, easy-to-use library that simplifies generating and decoding QR Codes in .NET applications, including .NET MAUI mobile apps for QR and Barcode scanning functionality. It provides fast and reliable solutions for integrating QR Code and Barcode scanning functionality across platforms such as iOS, Android, macOS, and Windows, which is essential for building cross-platform mobile apps.

Features of IronQR for .NET MAUI Mobile Apps

a. Cross-Platform Support: Works seamlessly across iOS, Android, macOS, and Windows platforms within MAUI apps.

b. QR Code Scanning: Efficiently decodes various types of QR Codes (URLs, text, contact information, etc.). It also supports multiple Barcodes read with efficient Barcode detection algorithms.

c. QR Code Generation: This allows for the easy generation of QR Codes from data like URLs, texts, and more.

d. Camera Permission Handling: Automatically handles camera permission requests, simplifying the scanning process.

e. High Performance: Fast and reliable QR Code scanning and generation with minimal resource usage.

f. Customizable Settings: Offers customization options for scanning parameters and QR Code appearance.

g. Easy Integration: Simple API and minimal setup required to add QR Code scanning and generation to your .NET MAUI app.

h. Error Handling: Provides detailed error messages and troubleshooting, ensuring smooth functionality in various scenarios.

i. No External Dependencies: IronQR operates independently, reducing the need for third-party libraries or complex configurations, unlike the ZXing Barcode scanner.

j. Multi-Format Support: Supports multiple QR Code formats, ensuring compatibility with a wide range of QR Codes used in the real world.

Pre-requisites

Before proceeding with the implementation, ensure that you have the following pre-requisites:

  1. Visual Studio 2022 or later installed.

  2. .NET 6.0 SDK or later (as .NET MAUI is built on .NET 6 and later versions).

  3. IronQR NuGet Package for QR Code scanning and Barcode detection.

  4. .NET MAUI app (You can create a new MAUI app in Visual Studio if you don't have one already).

Step 1: Create a .NET MAUI Project

To begin, let’s create a simple .NET MAUI project:

  1. Open Visual Studio and click on Create a new project.

  2. Select the .NET MAUI App template.

    New Project

  3. Name the project (e.g., MauiQRCodeScanner), select a location, and click Next.

    Project Configuration

  4. Select the required .NET version and click Create.

    Target Framework

Step 2: Install the IronQR NuGet package

IronQR is a third-party library that provides QR Code generation and scanning functionalities. To install IronQR, you need to add it via NuGet:

  1. In Visual Studio, right-click on the Dependencies in your Solution Explorer.

  2. Click Manage NuGet Packages.

  3. In the Browse tab, search for IronQR and click Install on the relevant package (usually IronQR or IronQR.Maui if specifically available for MAUI).

  4. Accept any licenses and ensure that the library gets installed.

    IronQR

Step 3: Set up Permissions for camera and file storage

For your application to scan QR Codes, you'll need to request camera permissions on mobile platforms (iOS and Android). Here's how you can add the following permissions inside.

Android device: In the AndroidManifest.xml file, add the camera permission:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
iOS: In the Info.plist file, add the camera usage description:

<key>NSCameraUsageDescription</key>
<string>We need access to your camera to scan QR codes</string>

Step 4: Implementing the QR Code Scanner

Now, let’s create a simple UI for our QR scanner in the MAUI Barcode scanner app. We will use the Button to trigger the scanning process and a Label to display the scanned QR Code text.

Edit the MainPage.xaml file in the XML namespace.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="MauiQRCodeScanner.MainPage">

    <StackLayout Padding="20" VerticalOptions="Center">
        <Button x:Name="scanButton" Text="Scan QR Code" Clicked="OnScanButtonClicked" />
        <Label x:Name="resultLabel" Text="Scan Result will appear here" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"/>
    </StackLayout>
</ContentPage>

Now, in the MainPage.xaml.cs, you will handle the camera permissions and the QR Code scanning logic. Here’s how to implement it:

using IronQrCode;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Essentials;

namespace MauiQRCodeScanner;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
    License.LicenseKey = "Your key";
        InitializeComponent();
    }

// OnScanButtonClicked method with object sender as input
    private async void OnScanButtonClicked(object sender, EventArgs e)
    {
        // Check for camera permission for var barcode with clear and valid reason
        var status = await Permissions.RequestAsync<Permissions.Camera>();
        if (status != PermissionStatus.Granted)
        {
            await DisplayAlert("Permission Denied", "Cannot scan QR codes without camera permission", "OK");
            return;
        }

        // Start scanning QR codes
        try
{
        var images = await FilePicker.Default.PickAsync(new PickOptions
        {
           PickerTitle = "Pick image",
          FileTypes = FilePickerFileType.Images
        });
        var imageSource = images.FullPath.ToString();
        // barcodeImage.Source = imageSource;

        var inputBmp = AnyBitmap.FromFile(imageSource);
        // Load the asset into QrImageInput
        QrImageInput imageInput = new QrImageInput(inputBmp);

        // Create a QR Reader object
        QrReader reader = new QrReader();

        // Read the input and get all embedded QR Codes
        IEnumerable<QrResult> results = reader.Read(imageInput);

        if (results.Any())
        {
            resultLabel.Text = "Scanned Text: " + results.First().Value; 
            // Display the result
        }
        else
        {
            resultLabel.Text = "No QR code detected";
        }
    }
    catch (Exception ex)
    {
           resultLabel.Text = "Error: " + ex.Message;
    }
    }
}
using IronQrCode;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Essentials;

namespace MauiQRCodeScanner;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
    License.LicenseKey = "Your key";
        InitializeComponent();
    }

// OnScanButtonClicked method with object sender as input
    private async void OnScanButtonClicked(object sender, EventArgs e)
    {
        // Check for camera permission for var barcode with clear and valid reason
        var status = await Permissions.RequestAsync<Permissions.Camera>();
        if (status != PermissionStatus.Granted)
        {
            await DisplayAlert("Permission Denied", "Cannot scan QR codes without camera permission", "OK");
            return;
        }

        // Start scanning QR codes
        try
{
        var images = await FilePicker.Default.PickAsync(new PickOptions
        {
           PickerTitle = "Pick image",
          FileTypes = FilePickerFileType.Images
        });
        var imageSource = images.FullPath.ToString();
        // barcodeImage.Source = imageSource;

        var inputBmp = AnyBitmap.FromFile(imageSource);
        // Load the asset into QrImageInput
        QrImageInput imageInput = new QrImageInput(inputBmp);

        // Create a QR Reader object
        QrReader reader = new QrReader();

        // Read the input and get all embedded QR Codes
        IEnumerable<QrResult> results = reader.Read(imageInput);

        if (results.Any())
        {
            resultLabel.Text = "Scanned Text: " + results.First().Value; 
            // Display the result
        }
        else
        {
            resultLabel.Text = "No QR code detected";
        }
    }
    catch (Exception ex)
    {
           resultLabel.Text = "Error: " + ex.Message;
    }
    }
}
Imports IronQrCode
Imports Microsoft.Maui.Controls
Imports Microsoft.Maui.Essentials

Namespace MauiQRCodeScanner

	Partial Public Class MainPage
		Inherits ContentPage

		Public Sub New()
		License.LicenseKey = "Your key"
			InitializeComponent()
		End Sub

	' OnScanButtonClicked method with object sender as input
		Private Async Sub OnScanButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
			' Check for camera permission for var barcode with clear and valid reason
			Dim status = Await Permissions.RequestAsync(Of Permissions.Camera)()
			If status <> PermissionStatus.Granted Then
				Await DisplayAlert("Permission Denied", "Cannot scan QR codes without camera permission", "OK")
				Return
			End If

			' Start scanning QR codes
			Try
			Dim images = Await FilePicker.Default.PickAsync(New PickOptions With {
				.PickerTitle = "Pick image",
				.FileTypes = FilePickerFileType.Images
			})
			Dim imageSource = images.FullPath.ToString()
			' barcodeImage.Source = imageSource;

			Dim inputBmp = AnyBitmap.FromFile(imageSource)
			' Load the asset into QrImageInput
			Dim imageInput As New QrImageInput(inputBmp)

			' Create a QR Reader object
			Dim reader As New QrReader()

			' Read the input and get all embedded QR Codes
			Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)

			If results.Any() Then
				resultLabel.Text = "Scanned Text: " & results.First().Value
				' Display the result
			Else
				resultLabel.Text = "No QR code detected"
			End If
		Catch ex As Exception
			   resultLabel.Text = "Error: " & ex.Message
		End Try
		End Sub
	End Class
End Namespace
VB   C#

Input QR Code

QR Code Input

Output

QR Code Output

Select the required QR Code or capture it from the Camera feed.

Select QR Code

The result is displayed in the UI as below.

QR Code UI Output

Code Explanation

Permissions: We request camera permissions using Permissions.RequestAsync(). If the permission is denied, the user is shown an alert.

IronQR Scanner: The IronQrCode.Scanner() class is used to scan QR Codes. The ScanAsync() method triggers the scanning, and the result is stored in scanResult. The scanned QR Code's text is displayed in the resultLabel.

Testing the QR Code Scanner: Now, you are ready to test the QR Code scanner. When the application runs, clicking the "Scan QR Code" button will initiate the scanning process. If a valid QR Code is in front of the camera, it will be decoded and displayed on the screen.

IronQR License (Trial Available)

IronQR works with a license key in the mobile app code. Developers can easily get a trial license from the license page. Place the license somewhere in the code as below before using the IronQR library.

License.LicenseKey = "Your License";
License.LicenseKey = "Your License";
License.LicenseKey = "Your License"
VB   C#

Conclusion

In this article, we walked through the process of building a QR Code scanner in a .NET MAUI application using IronQR. We started by setting up a .NET MAUI app, installed the IronQR package, and implemented the UI and scanning logic. IronQR makes QR Code scanning in a .NET MAUI app incredibly simple and effective.

IronQR library is designed to be cross-platform, ensuring that apps built with .NET MAUI can access QR Code functionality consistently across all target devices, whether they are smartphones, tablets, or desktop systems. IronQR also supports features like automatic camera permission handling, making it easier to integrate QR Code scanning without the hassle of managing permissions manually.

In short, IronQR for .NET MAUI enables developers to quickly implement QR Code scanning and generation features in their mobile apps, streamlining development and improving the user experience across all platforms.

< PREVIOUS
Smart Watch QR Code Scanner (.NET Developer Tutorial)
NEXT >
How to Generate QR Codes in ASP .NET Core