如何在 iOS 上使用 .NET MAUI 讀取和寫入條碼

This article was translated from English: Does it need improvement?
Translated
View the article in English
Ios related to 如何在 iOS 上使用 .NET MAUI 讀取和寫入條碼

.NET MAUI(多平台應用程式 UI)基於 Xamarin.Forms 構建,為使用 .NET 開發跨平台應用程式提供了一個統一的框架。 它使開發者能夠創建可在 Android、iOS、macOS 和 Windows 上無縫運行的原生用戶介面,從而簡化應用程式開發流程。

BarCode.iOS 軟體包為 iOS 帶來了條碼支援!

IronBarcode iOS 套件

BarCode.iOS 軟體套件透過 .NET 跨平台專案在 iOS 裝置上啟用條碼功能。 不需要預設的條碼軟體包。

安裝 BarCode.iOS 套件

<! -- NuGet 函式庫下載指令標籤 ::開始 -->

用於 PDF 的 C# NuGet 庫
### 使用 NuGet 安裝
安裝 BarCode.iOS 套件
(按鈕)

建立一個 .NET MAUI 項目

在"多平台"部分,選擇".NET MAUI 應用程式"並繼續。

建立 .NET MAUI 應用程式項目

包含 BarCode.iOS 庫

可以透過多種方式新增庫。 最簡單的方法或許是使用 NuGet。

  1. 在 Visual Studio 中,以滑鼠右鍵按一下"依賴項 > NuGet",然後選擇"管理 NuGet 套件..."。
  2. 選擇"瀏覽"選項卡,搜尋"BarCode.iOS"。
  3. 選擇"BarCode.iOS"軟體包,然後點選"新增軟體包"。

為防止與其他平台出現問題,請修改 csproj 文件,使其僅在面向 iOS 平台時包含該軟體套件。 為了做到這一點:

  1. 右鍵點選專案的 *.csproj 文件,然後選擇"編輯專案文件"。
  2. 建立一個新的 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
  1. 將"BarCode.iOS" PackageReference 移到我們剛剛建立的 ItemGroup 中。

上述步驟將阻止"BarCode.iOS"軟體包在Android等平台上使用。 為此,請安裝BarCode.Android

設計應用程式介面

修改 XAML 文件,使其能夠接受用於產生條碼和二維碼的輸入值。 此外,還要新增一個按鈕,用於選擇要讀取條碼的文件。 以下是一個範例:

<?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 系統中,需要自訂文件路徑才能將文件匯出到"文件"應用程式。

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 模擬器並運行專案。

運行專案

這將向您展示如何運行項目和使用條碼功能。

Execute .NET MAUI App project

下載 .NET MAUI 應用程式項目

您可以下載本指南的完整程式碼。它以壓縮檔案的形式提供,您可以在 Visual Studio 中將其作為 .NET MAUI 應用程式專案開啟。

點擊此處下載項目。

常見問題解答

如何使用C#於iOS上創建和掃描條碼?

您可以使用.NET MAUI和BarCode.iOS套件於iOS上創建和掃描條碼。透過NuGet安裝該套件,設置您的專案,並使用提供的方法生成和讀取條碼。

建構.NET MAUI條碼掃描應用程式的先決條件有哪些?

確保您已安裝支援.NET MAUI的Visual Studio,並能透過NuGet訪問BarCode.iOS套件。設置過程將包括修改XAML用於使用者介面和C#用於條碼處理。

如何修改XAML檔案以用於.NET MAUI條碼掃描使用者介面?

在XAML檔案中,包含條碼值的輸入欄位、條碼操作按鈕及顯示結果的標籤,透過 VerticalStackLayoutHorizontalStackLayout 進行版面設計。

我應該使用哪種方法在.NET MAUI應用程式中生成條碼?

在MainPage類中使用 WriteBarcode 方法來生成條碼,利用 BarcodeWriter 類別並透過 SaveToDownloadsAsync 儲存文件。

如果條碼在我的應用程式中未能被識別,我該如何排除故障?

確保條碼文件正確選擇且可讀。使用 ReadBarcode 方法選擇和解碼條碼,檢查文件路徑和格式是否正確。

條碼應用程式中設定授權金鑰的目的為何?

在您的應用中設定授權金鑰,以確保您擁有條碼程式庫的完整功能而無限制,這在生產環境中是至關重要的。

如何保存生成的條碼為PDF或PNG格式?

利用 IsGeneratePdfChecked 屬性來決定輸出格式。如勾選,條碼將保存為PDF文件;否則將保存為PNG影像。

運行一個.NET MAUI條碼專案於iOS模擬器的過程是什麼?

設置專案後,在Visual Studio中選擇iOS模擬器作為部署目標,運行專案以在模擬環境中測試條碼功能。

如何下載一個.NET MAUI條碼掃描的示範專案?

提供一個完整的示範專案作為壓縮文件供下載,專案可以在Visual Studio中打開以探索條碼掃描於iOS上的實施細節。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。

準備好開始了嗎?
Nuget 下載 2,070,733 | 版本: 2026.2 剛剛發布