如何在 iOS 上使用 .NET MAUI 读取和写入条形码
.NET MAUI(跨平台应用程序用户界面)建立在Xamarin.Forms之上,为使用.NET开发跨平台应用程序提供了统一的框架。 它使开发人员能够创建在Android、iOS、macOS和Windows上无缝运行的原生用户界面,简化了应用程序开发过程。
BarCode.iOS软件包为iOS提供条码支持!
如何在 iOS 上使用 .NET MAUI 读取和写入条形码
IronBarcode iOS包
BarCode.iOS包通过.NET跨平台项目在iOS设备上实现条形码功能。 不需要原始BarCode包。
通过 NuGet 安装
安装 BarCode.iOS 包
创建一个.NET MAUI项目
在多平台部分中,选择.NET MAUI应用程序并继续。

包含BarCode.iOS库
这个库可以通过多种方式添加。 最简单的方法可能是使用NuGet。
- 在Visual Studio中,右键单击"Dependencies > NuGet"并选择"Manage NuGet Packages ..."。
- 选择"Browse"选项卡并搜索"BarCode.iOS"。
- 选择"BarCode.iOS"包并点击"Add Package"。
为防止与其他平台产生问题,可以修改csproj文件,使其仅在目标平台为iOS时包含该包。 为此:
-
右键点击项目的*.csproj文件,选择“编辑项目文件”。
-
创建一个新的ItemGroup元素,如下所示:
<ItemGroup Condition="$(TargetFramework.Contains('ios')) == true"> <PackageReference Include="BarCode.iOS" Version="2025.3.4" /> </ItemGroup>XML -
将"BarCode.iOS"的PackageReference移动到我们刚刚创建的ItemGroup中。
上述步骤将防止"BarCode.iOS"包在Android等平台上使用。 为此,请安装BarCode.Android。
设计应用接口
修改XAML文件以接收输入值来生成条形码和QR码。 还需要添加一个按钮,以便选择文档以读取条形码。 下面是一个示例:
<?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>
读取和写入条形码
从上面的MainPage.xaml代码中,我们可以看到复选框决定生成的条形码和二维码是否应该是PDF格式。 接下来,我们设置许可证密钥。 请使用试用或付费许可证密钥进行此步骤。
代码检查并检索barcodeInput变量的值,然后使用CreateBarcode方法生成条形码。 最后,它调用SaveToDownloadsAsync方法,在Android和iOS上适当保存文件。
在iOS上,需要自定义文件路径以将文档导出到Files应用程序。
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 Namespace最后,切换构建目标到iOS模拟器并运行项目。
运行项目
这将向您展示如何运行项目并使用条形码功能。
下载.NET MAUI应用程序项目
您可以下载本指南的完整代码。 它作为一个压缩文件提供,您可以在Visual Studio中将其打开为.NET MAUI应用程序项目。
常见问题
BarCode.iOS 包用于什么用途?
BarCode.iOS 包用于通过提供条码创建和扫描功能,在.NET跨平台项目中的iOS设备上启用条码功能。
如何在我的项目中安装 BarCode.iOS 包?
您可以在Visual Studio中使用NuGet管理NuGet软件包,搜索 'BarCode.iOS' 来安装 BarCode.iOS 包。然后,将该包添加到您的项目中。
BarCode.iOS 包可以在除了iOS之外的平台上使用吗?
不,BarCode.iOS 专门用于iOS平台。您应修改csproj文件使其仅在针对iOS时包含。对于Android,您应使用 BarCode.Android 包。
如何在.NET MAUI 应用程序中使用 IronBarcode 生成条码?
在.NET MAUI应用中, 您可以使用BarcodeWriter.CreateBarcode方法生成条形码,并在设置所需的输出格式后使用SaveToDownloadsAsync方法保存。
在.NET MAUI 应用程序中使用什么方法读取条码?
BarcodeReader.Read方法用于在.NET MAUI应用中根据文件类型从图像或PDF文件中读取条形码。
如何在PDF或PNG格式之间切换生成条码?
您可以在应用的界面中使用复选框来确定输出格式,然后在您的代码中选择相应的ToPdfBinaryData或ToPngBinaryData方法。
在iOS上运行并测试.NET MAUI 应用程序与IronBarcode需要什么环境?
要在iOS上运行并测试.NET MAUI 应用程序与IronBarcode,应将构建目标切换到iOS模拟器,并通过Visual Studio执行项目。
在.NET MAUI 应用程序中使用 IronBarcode 时是否需要使用许可证密钥?
是的,您需要在应用程序的主页中通过将其分配给IronBarCode.License.LicenseKey来设置试用或付费许可证密钥。
XAML 在设计条码操作的应用程序界面中起到什么作用?
XAML 用于设计用户界面,包括生成和读取条码的按钮和输入字段,作为.NET MAUI 应用程序开发过程的一部分。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。