Wie man Barcode auf iOS in .NET MAUI liest und schreibt
.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, native Benutzeroberflächen zu erstellen, die nahtlos auf Android, iOS, macOS und Windows funktionieren und den App-Entwicklungsprozess rationalisieren.
Das BarCode.iOS-Paket bietet Barcode-Unterstützung für iOS!!
Wie man Barcode auf iOS in .NET MAUI liest und schreibt
IronBarcode iOS Paket
Das BarCode.iOS-Paket ermöglicht Barcode-Funktionen auf iOS-Geräten über .NET-Plattform-übergreifende Projekte. Das standardmäßige BarCode-Paket wird nicht benötigt.
PM > Install-Package BarCode.iOS
Mit NuGet installieren
Install-Package BarCode.iOS
Ein .NET MAUI-Projekt erstellen
Wählen Sie unter dem Abschnitt Multiplattform die Option .NET MAUI App und fahren Sie fort.
Schließen Sie die BarCode.iOS-Bibliothek ein
Die Bibliothek kann auf verschiedene Weise hinzugefügt werden. Am einfachsten ist es vielleicht, wenn Sie NuGet verwenden.
Klicken Sie in Visual Studio mit der rechten Maustaste auf "Dependencies > Nuget" und wählen Sie "Manage NuGet Packages ...".
Wählen Sie die Registerkarte "Browse" und suchen Sie nach "BarCode.iOS".
Wählen Sie das Paket "BarCode.iOS" und klicken Sie auf "Paket hinzufügen".
Um Probleme mit anderen Plattformen zu vermeiden, ändern Sie die csproj-Datei so, dass sie das Paket nur dann enthält, wenn es für die iOS-Plattform bestimmt ist. Um dies zu tun:
Klicken Sie mit der rechten Maustaste auf die *.csproj-Datei für Ihr Projekt und wählen Sie "Projektdatei bearbeiten".
- Erstellen Sie ein neues ItemGroup-Element als solches:
<ItemGroup Condition="$(TargetFramework.Contains('ios')) == true">
<PackageReference Include="BarCode.iOS" Version="2025.3.4" />
</ItemGroup>
Verschieben Sie die "BarCode.iOS" PackageReference in die ItemGroup, die wir gerade erstellt haben.
Die oben genannten Schritte verhindern, dass das Paket "BarCode.iOS" auf Plattformen wie Android verwendet wird. Zu diesem Zweck installieren Sie stattdessen BarCode.Android.
Gestalten Sie die App-Oberfläche
Ändern Sie die XAML-Datei so, dass sie Eingabewerte für die Generierung von Barcodes und QR-Codes akzeptiert. Fügen Sie außerdem eine Schaltfläche hinzu, um ein Dokument zum Lesen eines Barcodes auszuwählen. Nachfolgend 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>
Barcodes lesen und schreiben
Aus dem obigen MainPage.xaml-Code können wir sehen, dass das Kontrollkästchen bestimmt, ob der generierte Barcode und QR-Code im PDF-Format sein soll. Als Nächstes setzen wir den Lizenzschlüssel. Bitte verwenden Sie für diesen Schritt entweder einen Test- oder einen bezahlten Lizenzschlüssel.
Der Code überprüft und ruft den Wert der Variablen barcodeInput ab und verwendet dann die CreateBarcode
-Methode, um den Barcode zu generieren. Schließlich wird die Methode SaveToDownloadsAsync
aufgerufen, die 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 Dateien-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";
}
private async void WriteBarcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(barcodeInput.Text))
{
var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
// Generate file name
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
await SaveToDownloadsAsync(fileData, fileName);
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
private async void WriteQRcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(qrInput.Text))
{
var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
// Generate file name
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
await SaveToDownloadsAsync(fileData, fileName);
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
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;
if (file.ContentType.Contains("pdf"))
{
result = BarcodeReader.ReadPdf(stream);
}
else
{
result = BarcodeReader.Read(stream);
}
string barcodeResult = "";
int count = 1;
result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
OutputText.Text = barcodeResult;
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
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";
}
private async void WriteBarcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(barcodeInput.Text))
{
var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
// Generate file name
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
await SaveToDownloadsAsync(fileData, fileName);
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
private async void WriteQRcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(qrInput.Text))
{
var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
// Generate file name
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
await SaveToDownloadsAsync(fileData, fileName);
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
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;
if (file.ContentType.Contains("pdf"))
{
result = BarcodeReader.ReadPdf(stream);
}
else
{
result = BarcodeReader.Read(stream);
}
string barcodeResult = "";
int count = 1;
result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
OutputText.Text = barcodeResult;
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
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
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)
' Generate file name
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())
' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
Await SaveToDownloadsAsync(fileData, fileName)
End If
Catch ex As Exception
' Handle exceptions
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
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)
' Generate file name
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())
' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
Await SaveToDownloadsAsync(fileData, fileName)
End If
Catch ex As Exception
' Handle exceptions
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
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
If file.ContentType.Contains("pdf") Then
result = BarcodeReader.ReadPdf(stream)
Else
result = BarcodeReader.Read(stream)
End If
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
' Handle exceptions
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
#If IOS Then
' 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
#End If
End Function
End Class
End Namespace
Wechseln Sie abschließend das Build-Ziel zu iOS Simulator und führen Sie das Projekt aus.
Das Projekt ausführen
Dies wird Ihnen zeigen, wie Sie das Projekt ausführen und die Barcode-Funktion verwenden können.

.NET MAUI App Projekt herunterladen
Sie können den vollständigen Code für diese Anleitung herunterladen. Er wird als gezippte Datei geliefert, die Sie in Visual Studio als .NET MAUI App-Projekt öffnen können.