IronBarcode 开始 iOS 上的安装设置 如何在 iOS 上使用 .NET MAUI 读取和写入条形码 Curtis Chau 已更新:八月 20, 2025 下载 IronBarcode NuGet 下载 DLL 下载 免费试用 法学硕士副本 法学硕士副本 将页面复制为 Markdown 格式,用于 LLMs 在 ChatGPT 中打开 向 ChatGPT 咨询此页面 在双子座打开 向 Gemini 询问此页面 在双子座打开 向 Gemini 询问此页面 打开困惑 向 Perplexity 询问有关此页面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 复制链接 电子邮件文章 This article was translated from English: Does it need improvement? Translated View the article in English .NET MAUI(跨平台应用程序用户界面)建立在Xamarin.Forms之上,为使用.NET开发跨平台应用程序提供了统一的框架。 它使开发人员能够创建在Android、iOS、macOS和Windows上无缝运行的原生用户界面,简化了应用程序开发过程。 BarCode.iOS包为iOS引入了条形码支持! 如何在 iOS 上使用 .NET MAUI 读取和写入条形码 下载用于在 iOS 上读写条形码的 C# 库 Create a .NET MAUI App project Edit the XAML file to add an activation button and display output text Edit the corresponding C# file to handle barcode recognition Download the sample project for a quick start IronBarcode iOS包 BarCode.iOS包通过.NET跨平台项目在iOS设备上实现条形码功能。 不需要原始BarCode包。 安装 BarCode.iOS 包 通过 NuGet 安装 安装 BarCode.iOS 包 nuget.org/packages/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> <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> <?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 读取和写入条形码 从上面的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 } } 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 最后,切换构建目标到iOS模拟器并运行项目。 运行项目 这将向您展示如何运行项目并使用条形码功能。 下载.NET MAUI应用程序项目 您可以下载本指南的完整代码。 它作为一个压缩文件提供,您可以在Visual Studio中将其打开为.NET MAUI应用程序项目。 点击这里下载项目。 常见问题解答 如何在iOS上使用C#创建和扫描条形码? 您可以使用.NET MAUI与BarCode.iOS包在iOS上创建和扫描条形码。通过NuGet安装该包,设置您的项目,使用提供的方法生成和读取条形码。 在.NET MAUI中构建条形码扫描应用程序的前置条件是什么? 确保您已安装支持.NET MAUI的Visual Studio,并通过NuGet访问BarCode.iOS包。设置包括修改XAML用于UI和C#用于条形码处理。 如何修改.NET MAUI中的XAML文件以用于条形码扫描UI? 在XAML文件中,包括用于条形码值的输入字段,条形码操作的按钮,以及显示结果的标签,使用VerticalStackLayout和HorizontalStackLayout进行布局。 在.NET MAUI应用中生成条形码应该使用什么方法? 在MainPage类中使用WriteBarcode方法生成条形码,利用BarcodeWriter类并使用SaveToDownloadsAsync保存文件。 如果条形码在我的应用中未被识别,我该如何排查问题? 确保条形码文件已正确选择并可读。使用ReadBarcode方法选择并解码条形码,检查正确的文件路径和格式。 在条形码应用中设置许可证秘钥的目的是什么? 在您的应用中设置许可证秘钥可确保您拥有条形码库的完整功能而无限制,对于生产环境至关重要。 如何将生成的条形码保存为PDF或PNG? 利用IsGeneratePdfChecked属性确定输出格式。如果选中,则条形码保存为PDF;否则,保存为PNG图像。 在iOS模拟器上运行.NET MAUI条形码项目的过程是什么? 在设置好您的项目后,在Visual Studio中选择iOS模拟器作为部署目标,然后运行项目以测试在模拟环境中的条形码功能。 如何下载用于.NET MAUI中的条形码扫描的示例项目? 一个完整的示例项目可作为压缩文件下载,可在Visual Studio中打开以探索iOS上条形码扫描的实现细节。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 准备开始了吗? Nuget 下载 1,979,979 | Version: 2025.11 刚刚发布 免费 NuGet 下载 总下载量:1,979,979 查看许可证