.NET MAUIでiOSのバーコードを読み書きする方法

チャクニット・ビン
チャクニット・ビン
2022年2月28日
更新済み 2024年12月17日
共有:
This article was translated from English: Does it need improvement?
Translated
View the article in English
Ios related to .NET MAUIでiOSのバーコードを読み書きする方法

.NET MAUI(Multi-platform App UI)は、Xamarin.Formsの上に構築されており、.NETを使用してクロスプラットフォームアプリケーションを開発するための統一フレームワークを提供します。 これにより、開発者はAndroid、iOS、macOS、Windowsでシームレスに機能するネイティブユーザーインターフェースを作成し、アプリ開発プロセスを効率化できます。

BarCode.iOS package はiOSにバーコードサポートをもたらします!!

IronBarcode iOS パッケージ

BarCode.iOS パッケージは、.NET クロスプラットフォームプロジェクトを通じて iOS デバイスでバーコード機能を有効にします。 バニラBarCodeパッケージは必要ありません。

PM > Install-Package BarCode.iOS
C# NuGetライブラリ for PDF

NuGetでインストール

Install-Package BarCode.iOS

.NET MAUIプロジェクトを作成

マルチプラットフォームセクションの下で、.NET MAUI Appを選択して続行します。

.NET MAUI アプリプロジェクトを作成

BarCode.iOSライブラリを含める

ライブラリはさまざまな方法で追加できます。 おそらく最も簡単なのは、NuGetを使用することです。

  1. Visual Studio内で、「依存関係 > Nuget」を右クリックし、「NuGet パッケージの管理 ...」を選択してください。

  2. 「ブラウズ」タブを選択し、「BarCode.iOS」を検索します。

  3. 「BarCode.iOS」パッケージを選択し、「パッケージを追加」をクリックします。

    他のプラットフォームでの問題を防ぐために、csprojファイルを修正してiOSプラットフォームをターゲットにする場合のみパッケージを含めるようにしてください。 そうするためには:

  4. プロジェクトの *.csproj ファイルを右クリックし、「プロジェクト ファイルの編集」を選択します。

  5. 次のとおり、新しい 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ファイルを変更して、バーコードおよび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

バーコードの読み取りと書き込み

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";
    }
    private async void WriteBarcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(barcodeInput.Text))
            {
                var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
                // Generate file name
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    private async void WriteQRcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(qrInput.Text))
            {
                var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
                // Generate file name
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    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;
                if (file.ContentType.Contains("pdf"))
                {
                    result = BarcodeReader.ReadPdf(stream);
                }
                else
                {
                    result = BarcodeReader.Read(stream);
                }
                string barcodeResult = "";
                int count = 1;
                result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
                OutputText.Text = barcodeResult;
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    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";
    }
    private async void WriteBarcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(barcodeInput.Text))
            {
                var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
                // Generate file name
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    private async void WriteQRcode(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(qrInput.Text))
            {
                var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
                // Generate file name
                string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
                // Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
                await SaveToDownloadsAsync(fileData, fileName);
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    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;
                if (file.ContentType.Contains("pdf"))
                {
                    result = BarcodeReader.ReadPdf(stream);
                }
                else
                {
                    result = BarcodeReader.Read(stream);
                }
                string barcodeResult = "";
                int count = 1;
                result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
                OutputText.Text = barcodeResult;
            }
        }
        catch (Exception ex)
        {
            // Handle exceptions
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }
    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
		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)
					' Generate file name
					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())
					' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
					Await SaveToDownloadsAsync(fileData, fileName)
				End If
			Catch ex As Exception
				' Handle exceptions
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub
		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)
					' Generate file name
					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())
					' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
					Await SaveToDownloadsAsync(fileData, fileName)
				End If
			Catch ex As Exception
				' Handle exceptions
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub
		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
					If file.ContentType.Contains("pdf") Then
						result = BarcodeReader.ReadPdf(stream)
					Else
						result = BarcodeReader.Read(stream)
					End If
					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
				' Handle exceptions
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub
		Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
#If IOS Then
			' 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
#End If
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

最後に、ビルドターゲットをiOSシミュレータに切り替えてプロジェクトを実行してください。

プロジェクトを実行

これは、プロジェクトを実行しバーコード機能を使用する方法を示します。

.NET MAUIアプリプロジェクトを実行する

.NET MAUI アプリプロジェクトをダウンロード

このガイドの完全なコードをダウンロードできます。これは.zipファイルとして提供され、Visual Studioで.NET MAUIアプリプロジェクトとして開くことができます。

プロジェクトをダウンロードするにはここをクリックしてください。

チャクニット・ビン
ソフトウェアエンジニア
ChaknithはIronXLとIronBarcodeで作業しています。彼はC#と.NETに深い専門知識を持ち、ソフトウェアの改善と顧客サポートを支援しています。ユーザーとの対話から得た彼の洞察は、より良い製品、文書、および全体的な体験に貢献しています。