如何在 .NET MAUI 中在 iOS 上读取和写入条形码

查克尼特·宾
查克尼特·宾
2022年二月28日
更新 2024年十二月17日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English
Ios related to 如何在 .NET MAUI 中在 iOS 上读取和写入条形码

.NET MAUI(多平台应用程序用户界面)构建于Xamarin.Forms之上,提供了一个统一的框架,用于使用.NET开发跨平台应用程序。 它使开发人员能够创建在 Android、iOS、macOS 和 Windows 上无缝运行的本地主界面,简化了应用程序开发过程。

BarCode.iOS package 为 iOS 提供条形码支持!!

IronBarcode iOS 包

BarCode.iOS 包通过 .NET 跨平台项目在 iOS 设备上实现条形码功能。 不需要原始的BarCode包。

PM > Install-Package BarCode.iOS
C# NuGet库用于PDF

使用 NuGet 安装

Install-Package BarCode.iOS

创建一个.NET MAUI项目

在多平台部分中,选择 .NET MAUI App 并继续。

创建.NET MAUI应用程序项目

包括BarCode.iOS库

可以通过多种方式添加库。 或许使用 NuGet 是最简单的方式。

  1. 在 Visual Studio 中,右键单击“依赖项 > NuGet”,然后选择“管理 NuGet 包...”。

  2. 选择“浏览”选项卡并搜索“BarCode.iOS”。

  3. 选择“BarCode.iOS”包并点击“添加包”。

    为了防止与其他平台发生问题,在针对 iOS 平台进行目标设置时,修改 csproj 文件以仅包含该包。 为了做到这一点:

  4. 右键单击项目的 *.csproj 文件,然后选择“编辑项目文件”。

  5. 创建一个新的 ItemGroup 元素,如下所示:
<ItemGroup Condition="$(TargetFramework.Contains('ios')) == true">
    <PackageReference Include="BarCode.iOS" Version="2025.3.4" />
</ItemGroup>
XML
  1. 将 "BarCode.iOS" 的 PackageReference 移动到我们刚刚创建的 ItemGroup 内。

    上述步骤将防止在诸如Android等平台上使用“BarCode.iOS”软件包。 为此,请改为安装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

读取和写入条形码

从上述 MainPage.xaml 代码中,我们可以看到复选框决定生成的条形码和二维码是否应为 PDF 格式。 接下来,我们设置许可证密钥。 请在此步骤中使用试用版或付费版许可证密钥。

代码检查并检索barcodeInput变量的值,然后使用CreateBarcode方法生成条形码。 最后,它调用SaveToDownloadsAsync方法,该方法能够在Android和iOS上正确保存文件。

在 iOS 上,导出文档到 文件 应用程序需要自定义文件路径。

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";
    }
    private async void WriteBarcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(barcodeInput.Text))
            {
                var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
                // Generate file name
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    private async void WriteQRcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(qrInput.Text))
            {
                var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
                // Generate file name
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    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;
                if (file.ContentType.Contains("pdf"))
                {
                    result = BarcodeReader.ReadPdf(stream);
                }
                else
                {
                    result = BarcodeReader.Read(stream);
                }
                string barcodeResult = "";
                int count = 1;
                result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
                OutputText.Text = barcodeResult;
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    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";
    }
    private async void WriteBarcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(barcodeInput.Text))
            {
                var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
                // Generate file name
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    private async void WriteQRcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(qrInput.Text))
            {
                var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
                // Generate file name
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    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;
                if (file.ContentType.Contains("pdf"))
                {
                    result = BarcodeReader.ReadPdf(stream);
                }
                else
                {
                    result = BarcodeReader.Read(stream);
                }
                string barcodeResult = "";
                int count = 1;
                result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
                OutputText.Text = barcodeResult;
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    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
		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)
					' Generate file name
					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())
					' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
					Await SaveToDownloadsAsync(fileData, fileName)
				End If
			Catch ex As Exception
				' Handle exceptions
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub
		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)
					' Generate file name
					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())
					' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
					Await SaveToDownloadsAsync(fileData, fileName)
				End If
			Catch ex As Exception
				' Handle exceptions
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub
		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
					If file.ContentType.Contains("pdf") Then
						result = BarcodeReader.ReadPdf(stream)
					Else
						result = BarcodeReader.Read(stream)
					End If
					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
				' Handle exceptions
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub
		Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
#If IOS Then
			' 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
#End If
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

最后,将构建目标切换为 iOS 模拟器并运行项目。

运行项目

这将向您展示如何运行项目并使用条形码功能。

执行 .NET MAUI 应用程序项目

下载 .NET MAUI 应用程序项目

您可以下载本指南的完整代码。它以压缩文件的形式提供,您可以将其作为.NET MAUI App项目在Visual Studio中打开。

点击此处下载项目。

查克尼特·宾
软件工程师
Chaknith 负责 IronXL 和 IronBarcode 的工作。他在 C# 和 .NET 方面拥有深厚的专业知识,帮助改进软件并支持客户。他从用户互动中获得的洞察力,有助于提升产品、文档和整体体验。