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) 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 bringt Barcode-Unterstützung auf iOS!!

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.

Install-Package BarCode.iOS
class="products-download-section">
data-modal-id="trial-license-after-download">
class="product-image"> C# NuGet-Bibliothek für PDF
class="product-info">

Installieren mit NuGet

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

Erstellen Sie ein .NET MAUI Projekt

Wählen Sie im Bereich Multiplattform .NET MAUI App aus und fahren Sie fort.

Erstellen Sie ein .NET MAUI App-Projekt

Das BarCode.iOS-Bibliothek einbinden

Die Bibliothek kann auf verschiedene Weise hinzugefügt werden. Die einfachste Methode ist vielleicht die Verwendung von NuGet.

  1. Klicken Sie innerhalb von Visual Studio mit der rechten Maustaste auf "Abhängigkeiten > Nuget" und wählen Sie "NuGet-Pakete verwalten ...".
  2. Wählen Sie die Registerkarte "Durchsuchen" und suchen Sie nach "BarCode.iOS".
  3. 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:

  1. Klicken Sie mit der rechten Maustaste auf die *.csproj-Datei Ihres Projekts und wählen Sie "Projektdatei bearbeiten".
  2. Erstellen Sie ein neues ItemGroup-Element wie folgt:
<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. 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 für diesen Zweck BarCode.Android.

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>
<?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

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 entweder einen Test- oder bezahlten Lizenzschlüssel für diesen Schritt.

Der Code überprüft und ruft den Wert aus der barcodeInput Variablen ab und verwendet dann die CreateBarcode-Methode, um den Barcode zu generieren. Schließlich ruft es die SaveToDownloadsAsync-Methode auf, 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 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
    }
}
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

Schließ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.

Ausführen eines .NET MAUI App-Projekts

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

Wie kann ich Barcodes auf iOS mit C# erstellen und scannen?

Sie können .NET MAUI mit dem BarCode.iOS-Paket verwenden, um Barcodes auf iOS zu erstellen und zu scannen. Installieren Sie das Paket über NuGet, richten Sie Ihr Projekt ein und verwenden Sie die bereitgestellten Methoden, um Barcodes zu generieren und zu lesen.

Was sind die Voraussetzungen für die Erstellung einer Barcode-Scan-App in .NET MAUI?

Stellen Sie sicher, dass Sie Visual Studio mit .NET MAUI-Unterstützung installiert haben und Zugriff auf das BarCode.iOS Paket über NuGet haben. Die Einrichtung umfasst die Modifikation von XAML für die UI und C# für die Barcode-Verwaltung.

Wie kann ich die XAML-Datei für die Barcode-Scan-UI in .NET MAUI modifizieren?

Fügen Sie in der XAML-Datei Eingabefelder für Barcode-Werte, Schaltflächen für Barcode-Operationen und Labels für die Ergebnisanzeige ein, verwenden Sie VerticalStackLayout und HorizontalStackLayout für das Layout.

Welche Methode sollte ich verwenden, um einen Barcode in einer .NET MAUI-App zu generieren?

Verwenden Sie die WriteBarcode-Methode in der MainPage-Klasse, um Barcodes zu generieren, nutzen Sie die BarcodeWriter-Klasse und speichern Sie Dateien mit SaveToDownloadsAsync.

Wie kann ich Fehler beheben, wenn der Barcode in meiner App nicht erkannt wird?

Stellen Sie sicher, dass die Barcode-Datei korrekt ausgewählt und lesbar ist. Verwenden Sie die ReadBarcode-Methode, um den Barcode auszuwählen und zu decodieren, und überprüfen Sie die korrekten Dateipfade und Formate.

Was ist der Zweck der Festlegung eines Lizenzschlüssels in der Barcode-App?

Die Festlegung eines Lizenzschlüssels in Ihrer App stellt sicher, dass Sie die volle Funktionalität der Barcode-Bibliothek ohne Einschränkungen nutzen können, was in Produktionsumgebungen entscheidend ist.

Wie kann ich einen generierten Barcode als PDF oder PNG speichern?

Verwenden Sie die IsGeneratePdfChecked-Eigenschaft, um das Ausgabedateiformat zu bestimmen. Wenn aktiviert, werden Barcodes als PDFs gespeichert, ansonsten als PNG-Bilder.

Wie ist der Prozess, um ein .NET MAUI Barcode-Projekt auf einem iOS-Simulator auszuführen?

Nach der Einrichtung Ihres Projekts wählen Sie den iOS-Simulator als Bereitstellungsziel in Visual Studio und führen das Projekt aus, um die Barcode-Funktionalität in der simulierten Umgebung zu testen.

Wie kann ich ein Musterprojekt für das Barcode-Scannen in .NET MAUI herunterladen?

Ein vollständiges Musterprojekt steht als gezippte Datei zum Download zur Verfügung, die in Visual Studio geöffnet werden kann, um die Implementierungsdetails des Barcode-Scannens auf iOS zu erkunden.

Curtis Chau
Technischer Autor

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 ...

Weiterlesen
Bereit anzufangen?
Nuget Downloads 1,935,276 | Version: 2025.11 gerade veröffentlicht