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 wielopłatformowych 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.
BarCode.iOS package umożliwia wsparcie kodów kreskowych na 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 wielopłatformowe .NET. Standardowy pakiet BarCode nie jest potrzebny.
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 uzyc 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 zrobic:
-
Kliknij prawym przyciskiem na plik *.csproj w swoim projekcie i wybierz "Edit Project File".
-
Utwórz nowy element ItemGroup w następujący sposób:
<ItemGroup Condition="$(TargetFramework.Contains('ios')) == true"> <PackageReference Include="BarCode.iOS" Version="2025.3.4" /> </ItemGroup>XML -
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>
Czytaj i pisz kody kreskowe
Na podstawie kodu MainPage.xaml powyzej widzimy, ze checkbox decyduje, czy wygenerowany kod kreskowy i kod QR powinien być w formacie PDF. Nastepne ustawiamy klucz licencyjny. Użyj klucza licencyjnego próbnego lub płatnego na tym etapie.
Kod sprawdza i pobiera wartość z zmiennej barcodeInput, następnie używa metody CreateBarcode do wygenerowania kodu kreskowego. Na koniec wywołuje metodę SaveToDownloadsAsync, która zapisuje plik odpowiednio dla Android 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
}
}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 NamespaceNa koniec zmień cel kompilacji na iOS Simulator i uruchom projekt.
Uruchom projekt
To pokaże, jak uruchomić projekt i używać 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.
Najczęściej zadawane pytania
Do czego sluzy pakiet BarCode.iOS?
Pakiet BarCode.iOS sluzy do wlaczania funkcji kodow kreskowych na urzadzeniach iOS w projektach .NET cross-platform, zapewniajac tworzenie i skanowanie kodow kreskowych.
Jak moge zainstalowac pakiet BarCode.iOS w moim projekcie?
Możesz zainstalować pakiet BarCode.iOS, korzystając z NuGet w Visual Studio, zarządzając pakietami NuGet i wyszukując 'BarCode.iOS'. Następnie dodaj pakiet do swojego projektu.
Czy pakiet BarCode.iOS może być używany na platformach innych niż iOS?
Nie, BarCode.iOS jest przeznaczony specjalnie dla platform iOS. Należy zmodyfikować plik csproj, aby uwzględnić go tylko podczas celowania na iOS. Dla Androida należy użyć pakietu BarCode.Android.
Jak wygenerowac kod kreskowy w aplikacji .NET MAUI uzywajac IronBarcode?
W aplikacji .NET MAUI możesz wygenerować kod kreskowy, używając metody BarcodeWriter.CreateBarcode i zapisując go za pomocą metody SaveToDownloadsAsync po ustawieniu żądanego formatu wyjściowego.
Jakie metody są używane do odczytywania kodów kreskowych w aplikacji .NET MAUI?
Metoda BarcodeReader.Read jest używana do odczytywania kodów kreskowych zarówno z obrazów, jak i plików PDF w aplikacji .NET MAUI, w zależności od typu pliku.
Jak mogę przełączać się między generowaniem kodów kreskowych w formacie PDF a PNG?
Możesz użyć pola wyboru w interfejsie swojej aplikacji, aby określić format wyjściowy, a następnie w kodzie wybrać odpowiednie metody ToPdfBinaryData lub ToPngBinaryData.
Jakie srodowisko jest wymagane do uruchomienia i testowania aplikacji .NET MAUI z IronBarcode na iOS?
Aby uruchomic i przetestowac aplikacje .NET MAUI z IronBarcode na iOS, nalezy przelaczyc cel kompilacji na symulator iOS i uruchomic projekt przez Visual Studio.
Czy konieczne jest uzycie klucza licencyjnego przy uzywaniu IronBarcode w aplikacji .NET MAUI?
Tak, musisz ustawic albo klucz licencyjny dla wersji probnej, albo platny klucz licencyjny na glownej stronie aplikacji, przypisujac go do IronBarCode.License.LicenseKey.
Jaka role odgrywa XAML w projektowaniu interfejsu aplikacji dla operacji na kodach kreskowych?
XAML jest używany do projektowania interfejsu użytkownika, w tym przycisków i pól wejściowych do generowania i odczytywania kodów kreskowych, jako część procesu tworzenia aplikacji .NET MAUI.
Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podręczników.