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

Curtis Chau
Curtis Chau
已更新: 2026年8月2日
ios

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

BarCode.iOS套件為iOS帶來條碼支持!

IronBarcode iOS 套件

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

PM > Install-Package BarCode.iOS

C# NuGet PDF 庫

使用 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>
    XML
  3. 將「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

讀寫條碼

從上面的 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
    }
}

最後,將建置目標切換到 iOS 模擬器並運行專案。

運行專案

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

Execute .NET MAUI App project

下載 .NET MAUI 應用程式項目

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

點擊這裡下載專案。

常見問題

BarCode.iOS 套件用於什麼用途?

BarCode.iOS 套件用於透過 .NET 的跨平台專案在 iOS 設備上實現條碼功能,提供條碼創建和掃描能力。

如何在我的專案中安裝 BarCode.iOS 套件?

您可以在 Visual Studio 使用 NuGet 管理 NuGet 套件並搜索 '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方法。

運行和測試 .NET MAUI 應用程式與 IronBarcode 在 iOS 上需要什麼環境?

要在 iOS 上運行和測試 .NET MAUI 應用程式與 IronBarcode,您應將構建目標切換為 iOS 模擬器,並通過 Visual Studio 執行該專案。

在 .NET MAUI 應用程式中使用 IronBarcode 時是否需要使用授權金鑰?

是的,您需要在應用程式的主頁中設定試用或付費授權金鑰,將其指派給IronBarCode.License.LicenseKey。

在設計條碼操作的應用程式介面時,XAML 扮演什麼角色?

XAML 用於設計 .NET MAUI 應用程式開發過程中的使用者介面,包括生成和讀取條碼的按鈕和輸入欄位。

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

閱讀更多

準備好開始了嗎?

NuGet 下載次數 2,564,559版本:2026.11剛剛發布