Lesen und Schreiben von Barcodes auf iOS in .NET MAUI
.NET MAUI (Multi-platform App UI) baut auf Xamarin.Forms auf und bietet ein einheitliches Framework zur Entwicklung plattformübergreifender Anwendungen mit .NET. Es ermöglicht Entwicklern die Erstellung nativer Benutzeroberflächen, die nahtlos auf Android, iOS, macOS und Windows funktionieren und dadurch den App-Entwicklungsprozess vereinfachen.
Das BarCode.iOS-Paket bietet Barcode-Unterstützung für iOS!
Lesen und Schreiben von BarCodes auf iOS in .NET MAUI
- Laden Sie die C#-Bibliothek herunter, um Barcodes auf iOS zu lesen und zu schreiben
- Erstellen Sie ein .NET MAUI App-Projekt
- Bearbeiten Sie die XAML-Datei, um eine Aktivierungsschaltfläche hinzuzufügen und Ausgabetext anzuzeigen
- Bearbeiten Sie die zugehörige C#-Datei, um die Barcode-Erkennung zu verarbeiten
- Laden Sie das Beispielprojekt für einen schnellen Einstieg herunter
IronBarcode iOS Paket
Das BarCode.iOS-Paket ermöglicht Barcode-Funktionen auf iOS-Geräten über .NET plattformübergreifende Projekte. Das Standard-BarCode-Paket ist nicht erforderlich.
Installation mit NuGet
Installieren-Paket BarCode.iOS
Erstellen Sie ein .NET MAUI Projekt
Wählen Sie im Bereich Multiplattform .NET MAUI App aus und fahren Sie fort.

Fügen Sie die BarCode.iOS-Bibliothek hinzu
Die Bibliothek kann auf verschiedene Weise hinzugefügt werden. Die einfachste Methode ist die Verwendung von NuGet.
- Klicken Sie innerhalb von Visual Studio mit der rechten Maustaste auf "Abhängigkeiten > NuGet" und wählen Sie "NuGet-Pakete verwalten ...".
- Wählen Sie die Registerkarte "Durchsuchen" und suchen Sie nach "BarCode.iOS".
- Wählen Sie das Paket "BarCode.iOS" aus und klicken Sie auf "Paket hinzufügen".
Um Probleme mit anderen Plattformen zu vermeiden, ändern Sie die csproj-Datei, sodass das Paket nur beim Zielen auf die iOS-Plattform enthalten ist. Um dies zu tun:
-
Klicken Sie mit der rechten Maustaste auf die *.csproj-Datei Ihres Projekts und wählen Sie "Projektdatei bearbeiten".
-
Erstellen Sie ein neues ItemGroup-Element wie folgt:
<ItemGroup Condition="$(TargetFramework.Contains('ios')) == true"> <PackageReference Include="BarCode.iOS" Version="2025.3.4" /> </ItemGroup>XML -
Verschieben Sie die "BarCode.iOS" PackageReference in die gerade erstellte ItemGroup.
Die obigen Schritte verhindern, dass das "BarCode.iOS" Paket auf Plattformen wie Android verwendet wird. Installieren Sie stattdessen BarCode.Android für diesen Zweck.
Gestaltung der App-Oberfläche
Bearbeiten Sie die XAML-Datei, um Eingabewerte für die Generierung von Barcodes und QR-Codes zu akzeptieren. Fügen Sie auch einen Knopf hinzu, um ein Dokument zum Lesen eines Barcodes auszuwählen. Unten ist ein Beispiel:
<?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>
Lesen und Schreiben von Barcodes
Aus dem oben gezeigten MainPage.xaml-Code sehen wir, dass das Kontrollkästchen bestimmt, ob der erzeugte Barcode und QR-Code im PDF-Format sein soll. Als Nächstes setzen wir den Lizenzschlüssel. Bitte verwenden Sie einen Test- oder bezahlten Lizenzschlüssel für diesen Schritt.
Der Code überprüft und ruft den Wert aus der barcodeInput-Variable ab und verwendet dann die CreateBarcode-Methode, um den Barcode zu erzeugen. Schließlich ruft er die SaveToDownloadsAsync-Methode auf, welche die Datei sowohl für Android als auch für iOS entsprechend speichert.
Auf iOS ist ein benutzerdefinierter Dateipfad erforderlich, um das Dokument in die Files Anwendung zu exportieren.
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 NamespaceSchließlich wechseln Sie das Build-Ziel auf den iOS-Simulator und führen das Projekt aus.
Das Projekt ausführen
Dies zeigt Ihnen, wie Sie das Projekt ausführen und die Barcode-Funktion nutzen können.
Laden Sie das .NET MAUI App-Projekt herunter
Sie können den vollständigen Code für diesen Leitfaden herunterladen. Er kommt als gezippte Datei, die Sie in Visual Studio als .NET MAUI App-Projekt öffnen können.
Klicken Sie hier, um das Projekt herunterzuladen.
Häufig gestellte Fragen
Wofür wird das BarCode.iOS-Paket verwendet?
Das BarCode.iOS-Paket wird verwendet, um Barcode-Funktionen auf iOS-Geräten in plattformübergreifenden .NET-Projekten zu ermöglichen, indem es Barcode-Erstellung und -Scan bereitstellt.
Wie kann ich das BarCode.iOS-Paket in meinem Projekt installieren?
Sie können das BarCode.iOS-Paket mithilfe von NuGet in Visual Studio installieren, indem Sie NuGet-Pakete verwalten und nach 'BarCode.iOS' suchen. Fügen Sie dann das Paket zu Ihrem Projekt hinzu.
Kann das BarCode.iOS-Paket auf anderen Plattformen als iOS verwendet werden?
Nein, BarCode.iOS ist speziell für iOS-Plattformen. Sie sollten die csproj-Datei so ändern, dass es nur dann eingeschlossen ist, wenn Sie iOS anvisieren. Für Android sollten Sie das BarCode.Android-Paket verwenden.
Wie erstelle ich einen Barcode in einer .NET MAUI-App mit IronBarcode?
In einer .NET MAUI-App können Sie einen Barcode mit der Methode BarcodeWriter.CreateBarcode generieren und ihn mit der Methode SaveToDownloadsAsync speichern, nachdem Sie das gewünschte Ausgabeformat festgelegt haben.
Welche Methode wird verwendet, um Barcodes in einer .NET MAUI-App zu lesen?
Die Methode BarcodeReader.Read wird verwendet, um Barcodes entweder aus Bildern oder PDF-Dateien in einer .NET MAUI-App zu lesen, je nach Dateityp.
Wie kann ich zwischen der Barcode-Erstellung im PDF- oder PNG-Format wechseln?
Sie können ein Kontrollkästchen in der Benutzeroberfläche Ihrer App verwenden, um das Ausgabeformat zu bestimmen, und dann entsprechend die Methoden ToPdfBinaryData oder ToPngBinaryData in Ihrem Code wählen.
Welche Umgebung ist erforderlich, um eine .NET MAUI-App mit IronBarcode auf iOS zu betreiben und zu testen?
Um eine .NET MAUI-App mit IronBarcode auf iOS zu betreiben und zu testen, sollten Sie das Build-Target auf einen iOS-Simulator umschalten und das Projekt über Visual Studio ausführen.
Ist es notwendig, einen Lizenzschlüssel zu verwenden, wenn IronBarcode in einer .NET MAUI-App verwendet wird?
Ja, Sie müssen entweder einen Test- oder einen bezahlten Lizenzschlüssel auf der Hauptseite Ihrer Anwendung festlegen, indem Sie ihn IronBarCode.License.LicenseKey zuweisen.
Welche Rolle spielt XAML bei der Gestaltung der App-Oberfläche für Barcode-Operationen?
XAML wird verwendet, um die Benutzeroberfläche, einschließlich Knöpfen und Eingabefeldern für die Erzeugung und das Lesen von Barcodes, im Rahmen des .NET MAUI-App-Entwicklungsprozesses zu gestalten.
Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender Handbücher.