如何在 .NET MAUI 中於 iOS 上讀取與寫入 BARCODE
.NET MAUI(多平台應用程式使用者介面)基於 Xamarin.Forms 建構,提供了一個統一的框架,用於以 .NET 開發跨平台應用程式。 它讓開發者能夠建立原生使用者介面,這些介面能在 Android、iOS、macOS 和 Windows 上無縫運作,從而簡化應用程式開發流程。
BarCode.iOS 套件為 iOS 帶來條碼支援!
如何在 .NET MAUI 中於 iOS 上讀取與寫入 BarCode
IronBarcode iOS 套件
BarCode.iOS 套件可透過 .NET 跨平台專案,在 iOS 裝置上啟用條碼功能。 無需使用標準版 BarCode 套件。
Install-Package BarCode.iOS
透過 NuGet 安裝
Install-Package BarCode.iOS
建立 .NET MAUI 專案
在"多平台"區段中,選擇 .NET MAUI App 並繼續。

包含 BarCode.iOS 函式庫
該函式庫可透過多種方式進行整合。 最簡單的方法或許是使用 NuGet。
- 在 Visual Studio 中,右鍵點擊"依賴項 > NuGet",然後選擇"管理 NuGet 套件..."。
- 選取"瀏覽"索引標籤,並搜尋"BarCode.iOS"。
- 選取"BarCode.iOS"套件,然後點擊"新增套件"。
為避免在其他平台上出現問題,請修改 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>
- 將"BarCode.iOS"的 PackageReference 移至我們剛建立的 ItemGroup 內。
上述步驟將防止"BarCode.iOS"套件在 Android 等平台上被使用。 為此,請改為安裝 BarCode.Android。
設計應用程式介面
修改 XAML 檔案,使其能接受用於生成 BarCode 和 QR 碼的輸入值。 此外,請加入一個按鈕,用於選取文件以讀取BARCODE。 以下為範例:
<?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>
讀取與寫入BarCode
從上方的 MainPage.xaml 程式碼中,我們可以看出該核取方塊決定了生成的 BarCode 和 QR 碼是否應採用 PDF 格式。 接下來,我們設定授權金鑰。 請在此步驟中使用試用授權或付費版授權金鑰。
程式碼會檢查並從 barcodeInput 變數中擷取值,然後使用 CreateBarcode 方法來產生 BarCode。 最後,它會呼叫 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
最後,將建置目標切換為 iOS 模擬器並執行專案。
執行專案
本文將向您展示如何執行此專案並使用BarCode功能。
下載 .NET MAUI 應用程式專案
您可以下載本指南的完整程式碼。該檔案為 ZIP 檔,您可在 Visual Studio 中將其開啟為 .NET MAUI App 專案。
常見問題
如何使用 C# 在 iOS 上創建和掃描條碼?
您可以使用 .NET MAUI 與 BarCode.iOS 套件在 iOS 上創建和掃描條碼。通過 NuGet 安裝該套件,設置您的專案,並使用提供的方法來生成和讀取條碼。
在 .NET MAUI 中構建條碼掃描應用程式的先決條件是什麼?
確保您已安裝支持 .NET MAUI 的 Visual Studio,並可通過 NuGet 獲取 BarCode.iOS 套件。設置將包括修改 XAML 以供 UI 使用,C# 則負責條碼處理。
如何修改 XAML 檔案以進行 .NET MAUI 的條碼掃描 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 上條碼掃描的實現細節。
IronBarcode支援批次處理條碼嗎?
是的,IronBarcode支援批次處理,允許開發者在一次操作中生成或讀取多個條碼,提升大規模應用的效率。

