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 le code-barres sur iOS
- Create a .NET MAUI App project
- Modifiez le fichier XAML pour ajouter un bouton d'activation et afficher le texte de sortie
- Modifiez le fichier C# correspondant pour gérer la reconnaissance des codes-barres
- Téléchargez l'exemple de projet 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 avec NuGet
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>XML -
Déplacez la référence du package "BarCode.iOS" à l'intérieur du ItemGroup 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. Dans ce cas, installez plutôt BarCode.Android.
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>
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 correctement le fichier 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
}
}Imports IronBarCode
Namespace IronBarcodeMauiIOS
Public Partial Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(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(sender As Object, 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(sender As Object, 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(sender As Object, 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
Using 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}" & vbCrLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End Using
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(fileData As Byte(), 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 NamespaceImports IronBarCode
Namespace IronBarcodeMauiIOS
Public Partial Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(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(sender As Object, 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(sender As Object, 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(sender As Object, 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
Using 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}" & vbCrLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End Using
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(fileData As Byte(), 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 NamespaceEnfin, 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.
Cliquez ici pour télécharger le projet.
Questions fréquemment posées
À quoi sert le package BarCode.iOS ?
Le package BarCode.iOS est utilisé pour activer les fonctionnalités de code-barres sur les appareils iOS dans les projets multiplateformes .NET en fournissant des capacités de création et de lecture de codes-barres.
Comment puis-je installer le package BarCode.iOS dans mon projet ?
Vous pouvez installer le package BarCode.iOS en utilisant NuGet dans Visual Studio en gérant les packages NuGet et en recherchant 'BarCode.iOS'. Ensuite, ajoutez le package à votre projet.
Le package BarCode.iOS peut-il être utilisé sur des plateformes autres qu'iOS ?
Non, BarCode.iOS est spécifiquement pour les plateformes iOS. Vous devez modifier le fichier csproj pour l'inclure uniquement lorsque vous ciblez iOS. Pour Android, vous devez utiliser le package BarCode.Android.
Comment générer un code-barres dans une application .NET MAUI en utilisant IronBarcode ?
Dans une application .NET MAUI, vous pouvez générer un code-barres en utilisant la méthode BarcodeWriter.CreateBarcode et l'enregistrer avec la méthode SaveToDownloadsAsync après avoir défini le format de sortie souhaité.
Quelle méthode est utilisée pour lire les codes-barres dans une application .NET MAUI ?
La méthode BarcodeReader.Read est utilisée pour lire les codes-barres à partir d'images ou de fichiers PDF dans une application .NET MAUI, selon le type de fichier.
Comment puis-je basculer entre la génération de codes-barres en format PDF ou PNG ?
Vous pouvez utiliser une case à cocher dans l'interface de votre application pour déterminer le format de sortie, puis choisir les méthodes ToPdfBinaryData ou ToPngBinaryData en conséquence dans votre code.
Quel environnement est requis pour exécuter et tester une application .NET MAUI avec IronBarcode sur iOS ?
Pour exécuter et tester une application .NET MAUI avec IronBarcode sur iOS, vous devez changer la cible de build pour un simulateur iOS et exécuter le projet via Visual Studio.
Est-il nécessaire d'utiliser une clé de licence lorsque vous utilisez IronBarcode dans une application .NET MAUI ?
Oui, vous devez définir soit une clé de licence d'essai, soit une clé de licence payante sur la page principale de votre application en l'assignant à IronBarCode.License.LicenseKey.
Quel rôle joue XAML dans la conception de l'interface de l'application pour les opérations de code-barres ?
XAML est utilisé pour concevoir l'interface utilisateur, y compris les boutons et les champs de saisie pour générer et lire des codes-barres, dans le cadre du processus de développement d'applications .NET MAUI.
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 et créer des manuels bien structurés et visuellement attrayants.