Cómo leer y escribir códigos de barras en iOS en .NET MAUI
.NET MAUI (Interfaz de usuario de aplicaciones multiplataforma) se basa en Xamarin.Forms, proporcionando un marco unificado para desarrollar aplicaciones multiplataforma con .NET. Permite a los desarrolladores crear interfaces de usuario nativas que funcionan sin problemas en Android, iOS, macOS y Windows, agilizando el proceso de desarrollo de aplicaciones.
El paquete BarCode.iOS aporta soporte de código de barras a iOS.
Cómo leer y escribir códigos de barras en iOS en .NET MAUI
- Descargar la biblioteca de C# para leer y escribir códigos de barras en iOS
- Crear un proyecto de aplicación .NET MAUI
- Editar el archivo XAML para agregar un botón de activación y mostrar el texto de salida
- Editar el archivo C# correspondiente para gestionar el reconocimiento de códigos de barras
- Descargar el proyecto de ejemplo para un inicio rápido
Paquete IronBarcode para iOS
El paquete BarCode.iOS habilita funciones de códigos de barras en dispositivos iOS a través de proyectos multiplataforma .NET. No se necesita el paquete BarCode estándar.
Instalar con NuGet
Paquete de instalación BarCode.iOS
Crear un proyecto .NET MAUI
En la sección Multiplataforma, selecciona .NET MAUI App y continúa.

Incluir la biblioteca BarCode.iOS
La biblioteca se puede agregar de varias maneras. La más fácil es quizás usando NuGet.
- Dentro de Visual Studio, haz clic derecho en "Dependencies > NuGet" y selecciona "Manage NuGet Packages ...".
- Selecciona la pestaña "Browse" y busca "BarCode.iOS".
- Selecciona el paquete "BarCode.iOS" y haz clic en "Add Package".
Para evitar problemas con otras plataformas, modifica el archivo csproj para incluir el paquete solo al dirigirte a la plataforma iOS. Para hacerlo:
-
Haz clic derecho en el archivo *.csproj de tu proyecto y selecciona "Editar archivo del proyecto".
-
Crea un nuevo elemento ItemGroup de la siguiente manera:
<ItemGroup Condition="$(TargetFramework.Contains('ios')) == true"> <PackageReference Include="BarCode.iOS" Version="2025.3.4" /> </ItemGroup>XML -
Mueve el PackageReference de "BarCode.iOS" dentro del ItemGroup que acabamos de crear.
Los pasos anteriores evitarán que el paquete "BarCode.iOS" se utilice en plataformas como Android. Para ese propósito, instala BarCode.Android en su lugar.
Diseñar la interfaz de la aplicación
Modifica el archivo XAML para aceptar valores de entrada para generar códigos de barras y QR. Además, incluye un botón para seleccionar un documento para leer un código de barras. Ejemplo:
<?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>
Leer y escribir códigos de barras
Desde el código MainPage.xaml anterior, podemos ver que la casilla de verificación determina si el código de barras generado y el código QR debe estar en formato PDF. Configurar la clave de licencia. Por favor, usa una clave de licencia de prueba o de pago para este paso.
El código verifica y recupera el valor de la variable barcodeInput, luego utiliza el método CreateBarcode para generar el código de barras. Finalmente, llama al método SaveToDownloadsAsync, que guarda el archivo adecuadamente tanto para Android como para iOS.
En iOS, se requiere una ruta de archivo personalizada para exportar el documento a la aplicación Archivos.
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 NamespacePor último, cambia el objetivo de compilación a iOS Simulator y ejecuta el proyecto.
Ejecutar el proyecto
Esto te mostrará cómo ejecutar el proyecto y usar la función de código de barras.
Descargar proyecto de aplicación .NET MAUI
Puede descargar el código completo de esta guía. Viene como un archivo comprimido que puede abrir en Visual Studio como un proyecto de aplicación .NET MAUI.
Haga clic aquí para descargar el proyecto.
Preguntas frecuentes
¿Para qué se utiliza el paquete BarCode.iOS?
El paquete BarCode.iOS se utiliza para habilitar funciones de códigos de barras en dispositivos iOS dentro de proyectos multiplataforma .NET, proporcionando capacidades de creación y escaneo de códigos de barras.
¿Cómo puedo instalar el paquete BarCode.iOS en mi proyecto?
Puede instalar el paquete BarCode.iOS usando NuGet en Visual Studio gestionando Paquetes de NuGet y buscando 'BarCode.iOS'. Luego, añada el paquete a su proyecto.
¿El paquete BarCode.iOS se puede usar en plataformas distintas de iOS?
No, BarCode.iOS es específicamente para plataformas iOS. Deberías modificar el archivo csproj para incluirlo solo cuando se apunte a iOS. Para Android, deberías usar el paquete BarCode.Android.
¿Cómo genero un código de barras en una aplicación .NET MAUI usando IronBarcode?
En una aplicación .NET MAUI, puede generar un código de barras utilizando el método BarcodeWriter.CreateBarcode y guardarlo con el método SaveToDownloadsAsync después de establecer el formato de salida deseado.
¿Qué método se usa para leer códigos de barras en una aplicación .NET MAUI?
El método BarcodeReader.Read se utiliza para leer códigos de barras de imágenes o archivos PDF en una aplicación .NET MAUI, dependiendo del tipo de archivo.
¿Cómo puedo alternar entre generar códigos de barras en formato PDF o PNG?
Puede usar una casilla de verificación en la interfaz de su aplicación para determinar el formato de salida, y luego elegir entre los métodos ToPdfBinaryData o ToPngBinaryData según corresponda en su código.
¿Qué entorno se requiere para ejecutar y probar una aplicación .NET MAUI con IronBarcode en iOS?
Para ejecutar y probar una aplicación .NET MAUI con IronBarcode en iOS, deberías cambiar el objetivo de compilación a un iOS Simulator y ejecutar el proyecto a través de Visual Studio.
¿Es necesario usar una clave de licencia al usar IronBarcode en una aplicación .NET MAUI?
Sí, necesita establecer una clave de licencia de prueba o de pago en la página principal de su aplicación asignándola a IronBarCode.License.LicenseKey.
¿Qué papel desempeña XAML en el diseño de la interfaz para operaciones de códigos de barras?
XAML se utiliza para diseñar la interfaz de usuario, incluyendo botones y campos de entrada para generar y leer códigos de barras, como parte del proceso de desarrollo de aplicaciones .NET MAUI.
Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien estructurados y visualmente atractivos.