How to Read and Write Barcode on iOS in .NET MAUI

This article was translated from English: Does it need improvement?
Translated
View the article in English
class="container-fluid">
class="row">
class="col-md-2"> Ios related to How to Read and Write Barcode on iOS in .NET MAUI

.NET MAUI (Multi-platform App UI) s'appuie sur Xamarin.Forms, fournissant un cadre unifié pour développer des applications multiplateformes avec .NET. Il permet aux développeurs de créer des interfaces utilisateur natives qui fonctionnent de manière transparente sur Android, iOS, macOS et Windows, simplifiant ainsi le processus de développement d'applications.

Le package BarCode.iOS apporte la prise en charge des codes-barres à iOS !!

Package IronBarcode iOS

Le package BarCode.iOS permet d'ajouter des fonctionnalités de code-barres sur les appareils iOS via des projets multiplateformes .NET. Le package BarCode standard n'est pas nécessaire.

Install-Package BarCode.iOS

class="products-download-section">
data-modal-id="trial-license-after-download">
class="product-image"> C# NuGet Library for PDF
class="product-info">

Installer avec NuGet

class="copy-nuget-row">
Install-Package BarCode.iOS
class="copy-button">
class="nuget-link">nuget.org/packages/BarCode.iOS/

Créer un projet .NET MAUI

Dans la section Multiplattform, sélectionnez .NET MAUI App et continuez.

Créer un projet d'application .NET MAUI

Inclure la bibliothèque BarCode.iOS

La bibliothèque peut être ajoutée de différentes manières. La plus simple est peut-être d'utiliser NuGet.

  1. Dans Visual Studio, cliquez avec le bouton droit sur "Dépendances > NuGet" et sélectionnez "Gérer les packages NuGet...".
  2. Sélectionnez l'onglet "Parcourir" et recherchez "BarCode.iOS".
  3. Sélectionnez le package "BarCode.iOS" et cliquez sur "Ajouter le paquet".

Pour éviter les problèmes avec d'autres plateformes, modifiez le fichier csproj pour n'inclure le package que lors du ciblage de la plateforme iOS. Pour ce faire :

  1. Faites un clic droit sur le fichier *.csproj de votre projet et sélectionnez « Modifier le fichier projet ».
  2. Créez un nouvel élément ItemGroup comme suit :
<ItemGroup Condition="$(TargetFramework.Contains('ios')) == true">
    <PackageReference Include="BarCode.iOS" Version="2025.3.4" />
</ItemGroup>
<ItemGroup Condition="$(TargetFramework.Contains('ios')) == true">
    <PackageReference Include="BarCode.iOS" Version="2025.3.4" />
</ItemGroup>
XML
  1. Déplacez l'ItemGroup de "BarCode.iOS" que nous venons de créer.

Les étapes ci-dessus empêcheront le package "BarCode.iOS" d'être utilisé sur des plateformes telles que Android. À cet effet, installez BarCode.Android à la place.

Concevoir l'interface de l'application

Modifiez le fichier XAML pour accepter des valeurs d'entrée pour générer des codes-barres et des codes QR. Inclure également un bouton pour sélectionner un document pour la lecture d'un code-barres. Voici un exemple :

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="IronBarcodeMauiIOS.MainPage">

    <VerticalStackLayout Padding="20">
        <HorizontalStackLayout>
            <CheckBox x:Name="generatePdfCheckBox" IsChecked="{Binding IsGeneratePdfChecked}" />
            <Label Text="PDF (unchecked for PNG)" VerticalOptions="Center"/>
        </HorizontalStackLayout>

        <Entry x:Name="barcodeInput" Placeholder="Enter barcode value..." />
        <Button Text="Generate and save barcode" Clicked="WriteBarcode" />

        <Entry x:Name="qrInput" Placeholder="Enter QR code value..." />
        <Button Text="Generate and save QR code" Clicked="WriteQRcode" />

        <Button
        Text="Read Barcode"
        Clicked="ReadBarcode"
        Grid.Row="0"
        HorizontalOptions="Center"
        Margin="20, 20, 20, 10"/>
        <ScrollView
        Grid.Row="1"
        BackgroundColor="LightGray"
        Padding="10"
        Margin="10, 10, 10, 30">
            <Label x:Name="OutputText"/>
        </ScrollView>
    </VerticalStackLayout>

</ContentPage>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="IronBarcodeMauiIOS.MainPage">

    <VerticalStackLayout Padding="20">
        <HorizontalStackLayout>
            <CheckBox x:Name="generatePdfCheckBox" IsChecked="{Binding IsGeneratePdfChecked}" />
            <Label Text="PDF (unchecked for PNG)" VerticalOptions="Center"/>
        </HorizontalStackLayout>

        <Entry x:Name="barcodeInput" Placeholder="Enter barcode value..." />
        <Button Text="Generate and save barcode" Clicked="WriteBarcode" />

        <Entry x:Name="qrInput" Placeholder="Enter QR code value..." />
        <Button Text="Generate and save QR code" Clicked="WriteQRcode" />

        <Button
        Text="Read Barcode"
        Clicked="ReadBarcode"
        Grid.Row="0"
        HorizontalOptions="Center"
        Margin="20, 20, 20, 10"/>
        <ScrollView
        Grid.Row="1"
        BackgroundColor="LightGray"
        Padding="10"
        Margin="10, 10, 10, 30">
            <Label x:Name="OutputText"/>
        </ScrollView>
    </VerticalStackLayout>

</ContentPage>
XML

Lire et écrire des codes-barres

À partir du code MainPage.xaml ci-dessus, nous pouvons voir que la case à cocher détermine si le code-barres et le code QR générés doivent être au format PDF. Ensuite, nous définissons la clé de licence. Veuillez utiliser soit une clé de licence d'essai ou payée pour cette étape.

Le code vérifie et récupère la valeur de la variable barcodeInput, puis utilise la méthode CreateBarcode pour générer le code-barres. Enfin, il appelle la méthode SaveToDownloadsAsync, qui enregistre le fichier de manière appropriée pour Android et iOS.

Sur iOS, un chemin de fichier personnalisé est requis pour exporter le document vers l'application Fichiers.

using IronBarCode;
namespace IronBarcodeMauiIOS;
public partial class MainPage : ContentPage
{
    public bool IsGeneratePdfChecked
    {
        get => generatePdfCheckBox.IsChecked;
        set
        {
            generatePdfCheckBox.IsChecked = value;
        }
    }
    public MainPage()
    {
        InitializeComponent();
        IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
    }

    // Method to generate and save a barcode
    private async void WriteBarcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(barcodeInput.Text))
            {
                var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
                // Determine file extension based on checkbox state
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Save the file to the appropriate location
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Log exceptions to debug output
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }

    // Method to generate and save a QR code
    private async void WriteQRcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(qrInput.Text))
            {
                var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
                // Determine file extension based on checkbox state
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Save the file to the appropriate location
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Log exceptions to debug output
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }

    // Method to read a barcode from a file
    private async void ReadBarcode(object sender, EventArgs e)
    {
        try
        {
            var options = new PickOptions
            {
                PickerTitle = "Please select a file"
            };
            var file = await FilePicker.PickAsync(options);
            OutputText.Text = "";
            if (file != null)
            {
                using var stream = await file.OpenReadAsync();
                BarcodeResults result;
                // Determine if the document is a PDF or an image
                if (file.ContentType.Contains("pdf"))
                {
                    result = BarcodeReader.ReadPdf(stream);
                }
                else
                {
                    result = BarcodeReader.Read(stream);
                }
                // Display the results
                string barcodeResult = "";
                int count = 1;
                result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
                OutputText.Text = barcodeResult;
            }
        }
        catch (Exception ex)
        {
            // Log exceptions to debug output
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }

    // Method to save file data to the Downloads folder (or Documents on iOS)
    public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
    {
        // #if IOS
        // Define the custom path you want to save to
        var customPath = "/Users/Iron/Library/Developer/CoreSimulator/Devices/7D1F57F2-1103-46DA-AEE7-C8FC871502F5/data/Containers/Shared/AppGroup/37CD82C0-FCFC-45C7-94BB-FFEEF7BAFF13/File Provider Storage/Document";
        // Combine the custom path with the file name
        var filePath = Path.Combine(customPath, fileName);
        try
        {
            // Create the directory if it doesn't exist
            if (!Directory.Exists(customPath))
            {
                Directory.CreateDirectory(customPath);
            }
            // Save the file to the specified path
            await File.WriteAllBytesAsync(filePath, fileData);
            // Display a success message
            await Application.Current.MainPage.DisplayAlert("Saved", $"File saved to {filePath}", "OK");
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
        }
        // #endif
    }
}
using IronBarCode;
namespace IronBarcodeMauiIOS;
public partial class MainPage : ContentPage
{
    public bool IsGeneratePdfChecked
    {
        get => generatePdfCheckBox.IsChecked;
        set
        {
            generatePdfCheckBox.IsChecked = value;
        }
    }
    public MainPage()
    {
        InitializeComponent();
        IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
    }

    // Method to generate and save a barcode
    private async void WriteBarcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(barcodeInput.Text))
            {
                var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
                // Determine file extension based on checkbox state
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Save the file to the appropriate location
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Log exceptions to debug output
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }

    // Method to generate and save a QR code
    private async void WriteQRcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(qrInput.Text))
            {
                var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
                // Determine file extension based on checkbox state
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Save the file to the appropriate location
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Log exceptions to debug output
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }

    // Method to read a barcode from a file
    private async void ReadBarcode(object sender, EventArgs e)
    {
        try
        {
            var options = new PickOptions
            {
                PickerTitle = "Please select a file"
            };
            var file = await FilePicker.PickAsync(options);
            OutputText.Text = "";
            if (file != null)
            {
                using var stream = await file.OpenReadAsync();
                BarcodeResults result;
                // Determine if the document is a PDF or an image
                if (file.ContentType.Contains("pdf"))
                {
                    result = BarcodeReader.ReadPdf(stream);
                }
                else
                {
                    result = BarcodeReader.Read(stream);
                }
                // Display the results
                string barcodeResult = "";
                int count = 1;
                result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
                OutputText.Text = barcodeResult;
            }
        }
        catch (Exception ex)
        {
            // Log exceptions to debug output
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }

    // Method to save file data to the Downloads folder (or Documents on iOS)
    public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
    {
        // #if IOS
        // Define the custom path you want to save to
        var customPath = "/Users/Iron/Library/Developer/CoreSimulator/Devices/7D1F57F2-1103-46DA-AEE7-C8FC871502F5/data/Containers/Shared/AppGroup/37CD82C0-FCFC-45C7-94BB-FFEEF7BAFF13/File Provider Storage/Document";
        // Combine the custom path with the file name
        var filePath = Path.Combine(customPath, fileName);
        try
        {
            // Create the directory if it doesn't exist
            if (!Directory.Exists(customPath))
            {
                Directory.CreateDirectory(customPath);
            }
            // Save the file to the specified path
            await File.WriteAllBytesAsync(filePath, fileData);
            // Display a success message
            await Application.Current.MainPage.DisplayAlert("Saved", $"File saved to {filePath}", "OK");
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
        }
        // #endif
    }
}
Imports Microsoft.VisualBasic
Imports IronBarCode
Namespace IronBarcodeMauiIOS
	Partial Public Class MainPage
		Inherits ContentPage

		Public Property IsGeneratePdfChecked() As Boolean
			Get
				Return generatePdfCheckBox.IsChecked
			End Get
			Set(ByVal value As Boolean)
				generatePdfCheckBox.IsChecked = value
			End Set
		End Property
		Public Sub New()
			InitializeComponent()
			IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
		End Sub

		' Method to generate and save a barcode
		Private Async Sub WriteBarcode(ByVal sender As Object, ByVal e As EventArgs)
			Try
				If Not String.IsNullOrEmpty(barcodeInput.Text) Then
					Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)
					' Determine file extension based on checkbox state
					Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
					Dim fileName As String = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
					Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
					' Save the file to the appropriate location
					Await SaveToDownloadsAsync(fileData, fileName)
				End If
			Catch ex As Exception
				' Log exceptions to debug output
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		' Method to generate and save a QR code
		Private Async Sub WriteQRcode(ByVal sender As Object, ByVal e As EventArgs)
			Try
				If Not String.IsNullOrEmpty(qrInput.Text) Then
					Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)
					' Determine file extension based on checkbox state
					Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
					Dim fileName As String = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
					Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())
					' Save the file to the appropriate location
					Await SaveToDownloadsAsync(fileData, fileName)
				End If
			Catch ex As Exception
				' Log exceptions to debug output
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		' Method to read a barcode from a file
		Private Async Sub ReadBarcode(ByVal sender As Object, ByVal e As EventArgs)
			Try
				Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
				Dim file = Await FilePicker.PickAsync(options)
				OutputText.Text = ""
				If file IsNot Nothing Then
					Dim stream = Await file.OpenReadAsync()
					Dim result As BarcodeResults
					' Determine if the document is a PDF or an image
					If file.ContentType.Contains("pdf") Then
						result = BarcodeReader.ReadPdf(stream)
					Else
						result = BarcodeReader.Read(stream)
					End If
					' Display the results
					Dim barcodeResult As String = ""
					Dim count As Integer = 1
					result.ForEach(Sub(x)
						barcodeResult &= $"barcode {count}: {x.Value}" & vbLf
						count += 1
					End Sub)
					OutputText.Text = barcodeResult
				End If
			Catch ex As Exception
				' Log exceptions to debug output
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		' Method to save file data to the Downloads folder (or Documents on iOS)
		Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
			' #if IOS
			' Define the custom path you want to save to
			Dim customPath = "/Users/Iron/Library/Developer/CoreSimulator/Devices/7D1F57F2-1103-46DA-AEE7-C8FC871502F5/data/Containers/Shared/AppGroup/37CD82C0-FCFC-45C7-94BB-FFEEF7BAFF13/File Provider Storage/Document"
			' Combine the custom path with the file name
			Dim filePath = Path.Combine(customPath, fileName)
			Try
				' Create the directory if it doesn't exist
				If Not Directory.Exists(customPath) Then
					Directory.CreateDirectory(customPath)
				End If
				' Save the file to the specified path
				Await File.WriteAllBytesAsync(filePath, fileData)
				' Display a success message
				Await Application.Current.MainPage.DisplayAlert("Saved", $"File saved to {filePath}", "OK")
			Catch ex As Exception
				System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
			End Try
			' #endif
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

Enfin, changez la cible de build sur iOS Simulator et exécutez le projet.

Exécuter le projet

Cela vous montrera comment exécuter le projet et utiliser la fonction de code-barres.

Exécuter le projet d'application .NET MAUI

Télécharger le projet d'application .NET MAUI

Vous pouvez télécharger le code complet pour ce guide. Il vient sous forme d'un fichier zippé que vous pouvez ouvrir dans Visual Studio en tant que projet d'application .NET MAUI.

Cliquez ici pour télécharger le projet.

Questions Fréquemment Posées

Comment puis-je créer et scanner des codes-barres sur iOS en utilisant C# ?

Vous pouvez utiliser .NET MAUI avec le package BarCode.iOS pour créer et scanner des codes-barres sur iOS. Installez le package via NuGet, configurez votre projet, et utilisez les méthodes fournies pour générer et lire les codes-barres.

Quelles sont les conditions préalables pour construire une application de numérisation de codes-barres en .NET MAUI ?

Assurez-vous d'avoir Visual Studio avec le support de .NET MAUI installé et l'accès au package BarCode.iOS via NuGet. La configuration comprendra la modification du XAML pour l'interface utilisateur et du C# pour la gestion des codes-barres.

Comment modifier le fichier XAML pour l'interface utilisateur de numérisation de codes-barres en .NET MAUI ?

Dans le fichier XAML, incluez des champs de saisie pour les valeurs de codes-barres, des boutons pour les opérations sur les codes-barres, et des labels pour afficher les résultats, en utilisant VerticalStackLayout et HorizontalStackLayout pour la disposition.

Quelle méthode dois-je utiliser pour générer un code-barres dans une application .NET MAUI ?

Utilisez la méthode WriteBarcode dans la classe MainPage pour générer des codes-barres, en utilisant la classe BarcodeWriter et en enregistrant les fichiers avec SaveToDownloadsAsync.

Comment puis-je résoudre les problèmes si le code-barres n'est pas reconnu dans mon application ?

Assurez-vous que le fichier de code-barres est correctement sélectionné et lisible. Utilisez la méthode ReadBarcode pour sélectionner et décoder le code-barres, en vérifiant les chemins d'accès et formats de fichiers corrects.

Quel est le but de définir une clé de licence dans l'application de codes-barres ?

Définir une clé de licence dans votre application garantit que vous avez la pleine fonctionnalité de la bibliothèque de codes-barres sans limitations, ce qui est crucial pour les environnements de production.

Comment puis-je enregistrer un code-barres généré en tant que PDF ou PNG ?

Utilisez la propriété IsGeneratePdfChecked pour déterminer le format de sortie. Si coché, les codes-barres sont enregistrés sous forme de PDF ; sinon, ils sont enregistrés en images PNG.

Quel est le processus pour exécuter un projet de code-barres .NET MAUI sur un simulateur iOS ?

Après avoir configuré votre projet, sélectionnez le simulateur iOS comme cible de déploiement dans Visual Studio, et exécutez le projet pour tester la fonctionnalité de code-barres dans l'environnement simulé.

Comment puis-je télécharger un projet d'exemple pour la numérisation de codes-barres en .NET MAUI ?

Un projet d'exemple complet est disponible au téléchargement sous forme de fichier zippé, qui peut être ouvert dans Visual Studio pour explorer les détails de l'implémentation de la numérisation de codes-barres sur iOS.

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 1,935,276 | Version : 2025.11 vient de sortir