Jak odczytywać i zapisywać BARCODE w systemie iOS w .NET MAUI
.NET MAUI (Multi-platform App UI) opiera się na Xamarin.Forms, zapewniając ujednoliconą platformę do tworzenia aplikacji wieloplatformowych przy użyciu .NET. Umożliwia to programistom tworzenie natywnych interfejsów użytkownika, które działają płynnie na systemach Android, iOS, macOS i Windows, usprawniając proces tworzenia aplikacji.
Pakiet BarCode.iOS zapewnia obsługę kodów kreskowych w systemie iOS!!
Jak odczytywać i zapisywać BARCODE w systemie iOS w .NET MAUI
Pakiet IronBarcode dla systemu iOS
Pakiet BarCode.iOS umożliwia korzystanie z funkcji kodów kreskowych na urządzeniach z systemem iOS poprzez projekty wieloplatformowe .NET. Standardowy pakiet BarCode nie jest potrzebny.
Install-Package BarCode.iOS
Zainstaluj za pomocą NuGet
Install-Package BarCode.iOS
Utwórz projekt .NET MAUI
W sekcji "Multiplatform" wybierz opcję "Aplikacja .NET MAUI" i kontynuuj.

Dołącz bibliotekę BarCode.iOS
Bibliotekę można dodać na różne sposoby. Najłatwiej jest użyć NuGet.
- W programie Visual Studio kliknij prawym przyciskiem myszy "Zależności > NuGet" i wybierz "Zarządzaj pakietami NuGet...".
- Wybierz zakładkę "Przeglądaj" i wyszukaj "BarCode.iOS".
- Wybierz pakiet "BarCode.iOS" i kliknij "Dodaj pakiet".
Aby uniknąć problemów z innymi platformami, zmodyfikuj plik csproj tak, aby dołączał pakiet tylko w przypadku platformy iOS. Aby to zrobić:
- Kliknij prawym przyciskiem na plik *.csproj w swoim projekcie i wybierz "Edit Project File".
- Utwórz nowy element ItemGroup, jak poniżej:
<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>
- Przenieś odwołanie do pakietu "BarCode.iOS" do właśnie utworzonej grupy ItemGroup.
Powyższe kroki zapobiegną użyciu pakietu "BarCode.iOS" na platformach takich jak Android. W tym celu zainstaluj zamiast tego BarCode.Android.
Zaprojektuj interfejs aplikacji
Zmodyfikuj plik XAML tak, aby akceptował wartości wejściowe do generowania kodów BARCODE i kodów QR. Należy również dodać przycisk do wyboru dokumentu w celu odczytania BARCODE. Poniżej znajduje się przykład:
<?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>
Czytaj i pisz kody kreskowe
Na podstawie kodu MainPage.xaml powyżej widzimy, że checkbox decyduje, czy wygenerowany kod kreskowy i kod QR powinien być w formacie PDF. Następnie ustawiamy klucz licencyjny. Użyj proszę klucza licencyjnego próbnego lub płatnego dla tego kroku.
Kod sprawdza i pobiera wartość z zmiennej barcodeInput, a następnie wykorzystuje metodę CreateBarcode do wygenerowania kodu kreskowego. Na koniec wywołuje metodę SaveToDownloadsAsync, która zapisuje plik odpowiednio zarówno dla Androida, jak i iOS.
W systemie iOS do wyeksportowania dokumentu do aplikacji Pliki wymagana jest niestandardowa ścieżka do pliku.
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
Na koniec zmień cel kompilacji na iOS Simulator i uruchom projekt.
Uruchom projekt
To pokaże, jak uruchomić projekt i korzystać z funkcji kodu kreskowego.
Pobierz projekt aplikacji .NET MAUI
Możesz pobrać pełny kod do tego przewodnika. Jest dostępny jako spakowany plik, który możesz otworzyć w Visual Studio jako projekt .NET MAUI App.
Często Zadawane Pytania
Jak mogę tworzyć i skanować kody kreskowe w systemie iOS przy użyciu języka C#?
Możesz używać .NET MAUI z pakietem BarCode.iOS do tworzenia i skanowania kodów kreskowych na iOS. Zainstaluj pakiet przez NuGet, skonfiguruj swój projekt i użyj dostarczonych metod do generowania i odczytu kodów kreskowych.
Jakie są wymagania wstępne dotyczące tworzenia aplikacji do skanowania kodów kreskowych w .NET MAUI?
Upewnij się, że masz zainstalowane Visual Studio z obsługą .NET MAUI oraz dostęp do pakietu BarCode.iOS za pośrednictwem NuGet. Konfiguracja obejmie modyfikację XAML dla interfejsu użytkownika oraz C# dla obsługi kodów kreskowych.
Jak zmodyfikować plik XAML dla interfejsu użytkownika skanowania kodów kreskowych w .NET MAUI?
W pliku XAML należy uwzględnić pola wprowadzania wartości BARCODE, przyciski do operacji na BARCODE oraz etykiety do wyświetlania wyników, wykorzystując do układu elementy VerticalStackLayout i HorizontalStackLayout.
Jakiej metody należy użyć do wygenerowania BARCODE w aplikacji .NET MAUI?
Użyj metody WriteBarcode w klasie MainPage do generowania kodów kreskowych, wykorzystując klasę BarcodeWriter i zapisując pliki za pomocą SaveToDownloadsAsync.
Jak mogę rozwiązać problem, jeśli BarCode nie jest rozpoznawany w mojej aplikacji?
Upewnij się, że plik z kodem kreskowym jest poprawnie wybrany i czytelny. Użyj metody ReadBarcode, aby wybrać i zdekodować kod kreskowy, sprawdzając poprawność ścieżek i formatów plików.
Jaki jest cel ustawienia klucza licencyjnego w aplikacji do BarCode?
Ustawienie klucza licencyjnego w aplikacji zapewnia pełną funkcjonalność biblioteki BarCode bez ograniczeń, co ma kluczowe znaczenie w środowiskach produkcyjnych.
Jak mogę zapisać wygenerowany BarCode jako plik PDF lub PNG?
Użyj właściwości IsGeneratePdfChecked, aby określić format wyjściowy. Jeśli jest zaznaczona, barcodes są zapisywane jako pliki PDF; w przeciwnym razie są zapisywane jako obrazy PNG.
Jak wygląda proces uruchamiania projektu .NET MAUI z kodami BarCode na symulatorze iOS?
Po skonfigurowaniu projektu wybierz symulator iOS jako miejsce wdrożenia w Visual Studio i uruchom projekt, aby przetestować działanie BarCode w symulowanym środowisku.
Jak mogę pobrać przykładowy projekt do skanowania BarCode w .NET MAUI?
Kompletny przykładowy projekt jest dostępny do pobrania w postaci pliku ZIP, który można otworzyć w programie Visual Studio, aby zapoznać się ze szczegółami implementacji skanowania kodów kreskowych w systemie iOS.

