.NET MAUI で iOS 上のバーコードを読み書きする方法
.NET MAUI (マルチプラットフォームアプリUI) は Xamarin.Forms を基盤とし、.NETを使用してクロスプラットフォームアプリケーションを開発するための統一されたフレームワークを提供します。 これにより、開発者はAndroid、iOS、macOS、Windows上でシームレスに機能するネイティブユーザーインターフェイスを作成し、アプリ開発プロセスを効率化できます。
BarCode.iOSパッケージ は、iOSにバーコードサポートを提供します!
.NET MAUI で iOS 上のバーコードを読み書きする方法
IronBarcode iOSパッケージ
BarCode.iOSパッケージ は、.NETクロスプラットフォームプロジェクトを通じてiOSデバイスにバーコード機能を提供します。 バニラのBarCodeパッケージは必要ありません。
インストールパッケージ BarCode.iOS
Install with NuGet
インストールパッケージ BarCode.iOS
.NET MAUIプロジェクトの作成
マルチプラットフォームセクションで、.NET MAUI App を選択して続行します。

BarCode.iOSライブラリを含める
ライブラリを追加する方法はいくつかあります。 最も簡単なのは、おそらくNuGetを使用することです。
- Visual Studio 内で、"Dependencies > Nuget" を右クリックし、"Manage NuGet Packages ..." を選択します。
- "Browse" タブを選択し、"BarCode.iOS" を検索します。
- "BarCode.iOS" パッケージを選択し、"Add Package" をクリックします。
他のプラットフォームとの問題を防ぐために、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 をインストールします。
アプリインターフェースを設計する
バーコードとQRコードを生成するために入力値を受け入れるように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>バーコードを読み書きする
上記の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最後に、ビルドターゲットをiOSシミュレーターに切り替えてプロジェクトを実行します。
プロジェクトを実行する
これにより、プロジェクトを実行してバーコード機能を使用する方法が示されます。

.NET MAUIアプリプロジェクトをダウンロードする
このガイドの完全なコードをダウンロードできます。これは.zipファイルとして提供され、Visual Studioで.NET MAUIアプリプロジェクトとして開くことができます。
よくある質問
C#を使用してiOSでバーコードを作成およびスキャンするにはどうすればよいですか?
iOSでバーコードを作成およびスキャンするためにBarCode.iOSパッケージを使用して.NET MAUIを使用することができます。NuGetを介してパッケージをインストールし、プロジェクトを設定し、提供されたメソッドを使用してバーコードを生成および読み込みます。
NET MAUIでバーコードスキャンアプリを構築するための前提条件は何ですか?
Visual Studioに.NET MAUIサポートがインストールされ、NuGetを介してBarCode.iOSパッケージにアクセスできることを確認してください。セットアップにはUI用のXAMLとバーコード処理用のC#の変更が含まれます。
NET MAUIでバーコードスキャンUI用にXAMLファイルをどのように修正しますか?
XAMLファイルで、VerticalStackLayoutおよびHorizontalStackLayoutをレイアウトに使用して、バーコード値の入力フィールド、バーコード操作用のボタン、および結果を表示するためのラベルを含みます。
NET MAUIアプリでバーコードを生成するためにどのメソッドを使用すべきですか?
メインページクラスでWriteBarcodeメソッドを使用してバーコードを生成し、BarcodeWriterクラスを活用し、ファイルをSaveToDownloadsAsyncで保存します。
アプリでバーコードが認識されていない場合、どのようにトラブルシューティングしますか?
バーコードファイルが正しく選択され、読み取り可能であることを確認してください。ReadBarcodeメソッドを使用してバーコードを選択およびデコードし、ファイルパスとフォーマットが正しいことを確認します。
バーコードアプリでライセンスキーを設定する目的は何ですか?
アプリでライセンスキーを設定することで、制限なくバーコードライブラリのフル機能を有効にすることができ、これは本番環境で重要です。
生成されたバーコードをPDFまたはPNGとして保存するにはどうすればよいですか?
IsGeneratePdfCheckedプロパティを使用して出力形式を決定します。チェックされている場合、バーコードはPDFとして保存され、それ以外の場合はPNG画像として保存されます。
iOSシミュレータで.NET MAUIバーコードプロジェクトを実行するプロセスは何ですか?
プロジェクトを設定した後、Visual StudioでiOSシミュレータをデプロイメントターゲットとして選択し、シミュレートされた環境でバーコード機能をテストするためにプロジェクトを実行します。
NET MAUIでバーコードスキャン用のサンプルプロジェクトをどのようにダウンロードできますか?
完全なサンプルプロジェクトは、ダウンロード可能なジップファイルとして利用可能で、Visual Studioで開くことでiOSでのバーコードスキャンの実装詳細を探索することができます。






