Comment lire et écrire des codes-barres sur iOS avec .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 !!
Comment lire et écrire des codes-barres sur iOS avec .NET MAUI
- Téléchargez la bibliothèque C# pour lire et écrire des codes-barres sur iOS
- Créer un projet d'application .NET MAUI
- Modifier le fichier XAML pour ajouter un bouton d'activation et afficher le texte de sortie
- Modifier le fichier C# correspondant pour gérer la reconnaissance des codes-barres
- Télécharger le projet d'exemple pour un démarrage rapide
Paquet 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.
Installer le package BarCode.iOS
Installer le package BarCode.iOS
Créer un projet .NET MAUI
Dans la section Multiplattform, sélectionnez .NET MAUI App et continuez.

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.
- Dans Visual Studio, cliquez avec le bouton droit sur "Dépendances > NuGet" et sélectionnez "Gérer les packages NuGet...".
- Sélectionnez l'onglet "Parcourir" et recherchez "BarCode.iOS".
- Sélectionnez le package "BarCode.iOS" et cliquez sur "Ajouter le paquet".
Pour éviter des problèmes avec d'autres plateformes, modifiez le fichier csproj afin d'inclure le package uniquement lors du ciblage de la plateforme iOS. Pour ce faire :
- Faites un clic droit sur le fichier *.csproj de votre projet et sélectionnez " Modifier le fichier projet ".
- 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>
- 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>
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
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.
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.
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.

