IronBarcode 開始使用 iOS上的設定 How to Read and Write Barcode on iOS in .NET MAUI Curtis Chau 更新日期:8月 20, 2025 Download IronBarcode NuGet 下載 DLL 下載 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article This article was translated from English: Does it need improvement? Translated View the article in English class="container-fluid"> class="row"> class="col-md-2"> .NET MAUI(跨平台應用 UI)構建於 Xamarin.Forms 基礎上,提供一個統一的框架,用於使用 .NET 開發跨平台應用。 它使開發者能夠創建在 Android、iOS、macOS 和 Windows 上運行流暢的原生用戶界面,簡化應用開發過程。 BarCode.iOS 套件為 iOS 提供條碼支持! class="hsg-featured-snippet"> 如何在 .NET MAUI 上於 iOS 平台讀取和寫入條碼 下載 C# 函式庫以讀取和寫入 iOS 上的條碼 創建 .NET MAUI 應用項目 編輯 XAML 文件以添加激活按鈕和顯示輸出文本 編輯相應的 C# 文件以處理條碼識別 下載示例項目以快速開始 IronBarcode iOS 套件 BarCode.iOS 套件通過 .NET 跨平台項目為 iOS 設備啟用條碼功能。 不需要原始的 BarCode 套件。 Install-Package BarCode.iOS class="products-download-section"> data-modal-id="trial-license-after-download"> class="product-image"> class="product-info"> 使用 NuGet 安裝 data-original-title="點擊以複製"> class="copy-nuget-row"> Install-Package BarCode.iOS class="copy-button"> class="nuget-link">nuget.org/packages/BarCode.iOS/ 創建 .NET MAUI 項目 在多平台部分,選擇 .NET MAUI 應用並繼續。 包含 BarCode.iOS 函式庫 可以通過多種方式添加該庫。 最簡單的可能是使用 NuGet。 在 Visual Studio 中,右鍵單擊“Dependencies > 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> 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 代碼中,我們可以看到該復選框決定生成的條碼和 QR 碼是否應為 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 模擬器並運行項目。 運行項目 這將向您展示如何運行該項目並使用條碼功能。 下載 .NET MAUI 應用程式項目 您可以下載此指南的完整代碼。 它來作為一個壓縮文件,您可以在 Visual Studio 中打開它作為 .NET MAUI 應用程式項目。 點擊此處下載項目。 常見問題解答 如何使用 C# 在 iOS 上建立和掃描條碼? 您可以使用 .NET MAUI 和 BarCode.iOS 套件在 iOS 上建立和掃描條碼。透過 NuGet 安裝該套件,設定您的項目,然後使用提供的方法來產生和讀取條碼。 在 .NET MAUI 中建立條碼掃描應用程式需要哪些先決條件? 請確保您已安裝支援 .NET MAUI 的 Visual Studio,並透過 NuGet 取得 BarCode.iOS 套件。安裝過程將包括修改用於 UI 的 XAML 程式碼和用於條碼處理的 C# 程式碼。 如何在.NET MAUI中修改條碼掃描UI的XAML檔案? 在 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 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 準備好開始了嗎? Nuget 下載 1,935,276 | 版本: 2025.11 剛剛發布 免費 NuGet 下載 總下載量:1,935,276 查看許可證