.NET MAUI'de iOS'ta Barkod Okuma ve Yazma

This article was translated from English: Does it need improvement?
Translated
View the article in English
Ios related to .NET MAUI'de iOS'ta Barkod Okuma ve Yazma

.NET MAUI (Çoklu platform uygulama arayüzü), Xamarin.Forms üzerine inşa edilmiş olup .NET ile çapraz platform uygulamalar geliştirmek için birleştirilmiş bir çerçeve sağlar. Bu, geliştiricilerin Android, iOS, macOS ve Windows üzerinde sorunsuz çalışan yerel kullanıcı arayüzleri oluşturmalarını mümkün kılarak uygulama geliştirme sürecini kolaylaştırır.

BarCode.iOS paketi iOS için barkod desteği getirir!

IronBarcode iOS Paketi

BarCode.iOS paketi, .NET çapraz platform projeleri aracılığıyla iOS cihazlarında barkod özelliklerini etkinleştirir. Vanilya BarCode paketi gerekli değildir.

Install-Package BarCode.iOS
PDF için C# NuGet Kütüphanesi

NuGet ile yükleyin

Install-Package BarCode.iOS

Bir .NET MAUI Projesi Oluşturun

Çoklu platform bölümünde, .NET MAUI Uygulaması'nı seçin ve devam edin.

.NET MAUI Uygulama projesi oluşturma

BarCode.iOS Kütüphanesini Dahil Edin

Kütüphane çeşitli şekillerde eklenebilir. Belki de en kolay yol NuGet kullanmaktır.

  1. Visual Studio içinde, "Dependencies > NuGet" üzerine sağ tıklayın ve "NuGet Paketlerini Yönet..." seçeneğini seçin.
  2. "Gözat" sekmesini seçin ve "BarCode.iOS" arayın.
  3. "BarCode.iOS" paketini seçin ve "Paket Ekle" üzerine tıklayın.

Diğer platformlarla ilgili sorunları önlemek için csproj dosyasını yalnızca iOS platformunu hedeflerken paketi ekleyecek şekilde değiştirin. Bunu yapmak için:

  1. Projenizin *.csproj dosyası üzerine sağ tıklayın ve "Proje Dosyasını Düzenle" seçeneğini seçin.
  2. Yeni bir ItemGroup elementi oluşturun:
<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
  1. Yeni oluşturduğumuz ItemGroup içine "BarCode.iOS" PackageReference'ı taşıyın.

Yukarıdaki adımlar, "BarCode.iOS" paketinin Android gibi platformlarda kullanılmasını engelleyecektir. Bu amaçla, onun yerine BarCode.Android yükleyin.

Uygulama Arayüzünü Tasarlayın

Barkod ve QR kodları oluşturmak için giriş değerlerini kabul edecek şekilde XAML dosyasını değiştirin. Ayrıca, bir barkodu okumak için bir belge seçme butonu ekleyin. Aşağıda bir örnek verilmiştir:

<?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

Barkodları Okuyun ve Yazın

MainPage.xaml kodundan, üretilen barkod ve QR kodunun PDF formatında olup olmayacağını belirlemek için onay kutusunun karar verdiğini görebiliriz. Sonraki adım olarak lisans anahtarını ayarlayın. Bu adım için lütfen deneme ya da ücretli bir lisans anahtarı kullanın.

Kod, barcodeInput değişkenindeki değeri kontrol edip alır, ardından CreateBarcode yöntemini kullanarak BarCode'u oluşturur. Son olarak, hem Android hem de iOS için dosyayı uygun şekilde kaydeden SaveToDownloadsAsync yöntemini çağırır.

iOS'ta, belgeyi Dosyalar uygulamasına aktarmak için özel bir dosya yolu gereklidir.

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

Son olarak, derleme hedefini iOS Simülatörüne değiştirin ve projeyi çalıştırın.

Projeyi Çalıştırın

Bu, projenin nasıl çalıştırılacağını ve barkod özelliğinin nasıl kullanılacağını gösterecektir.

Execute .NET MAUI App project

.NET MAUI Uygulama Projesi İndirin

Bu kılavuzun tüm kodunu indirebilirsiniz. Visual Studio'da .NET MAUI Uygulama projesi olarak açabileceğiniz sıkıştırılmış bir dosya olarak gelir.

Projeyi indirmek için buraya tıklayın.

Sıkça Sorulan Sorular

iOS'ta C# kullanarak nasıl barkod oluşturabilir ve tarayabilirim?

.NET MAUI ile BarCode.iOS paketini kullanarak iOS'ta barkodlar oluşturabilir ve tarayabilirsiniz. Paketi NuGet aracılığıyla kurun, projenizi kurun ve barkod oluşturma ve okumak için sağlanan yöntemleri kullanın.

.NET MAUI'de barkod tarama uygulaması geliştirmek için ön koşullar nelerdir?

Visual Studio'da .NET MAUI desteği olduğundan ve BarCode.iOS paketine NuGet üzerinden erişiminiz olduğundan emin olun. Kurulumda UI için XAML'in ve barkod tanıması için C#'ın değiştirilmesi de bulunmaktadır.

.NET MAUI'de barkod tarama UI için XAML dosyasını nasıl düzenlerim?

XAML dosyasında barkod değerleri için giriş alanları, barkod işlemleri için düğmeler ve sonuçları göstermek için etiketler ekleyin. Düzen için VerticalStackLayout ve HorizontalStackLayout kullanın.

.NET MAUI uygulamasında barkod oluşturmak için hangi yöntemi kullanmalıyım?

MainPage sınıfındaki WriteBarcode yöntemini kullanarak BarcodeWriter sınıfından yararlanın ve dosyaları SaveToDownloadsAsync ile kaydedin.

Uygulamamda barkod tanımlanmıyorsa nasıl sorun giderebilirim?

Barkod dosyasının doğru seçildiğinden ve okunabilir olduğundan emin olun. Barkodu seçmek ve kodunu çözmek için ReadBarcode metodunu kullanın, dosya yolları ve formatlarını kontrol edin.

Barkod uygulamasında bir lisans anahtarı ayarlamanın amacı nedir?

Uygulamanızda bir lisans anahtarı ayarlamak, barkod kütüphanesinin kısıtlama olmadan tam işlevselliğine sahip olmanızı sağlar, bu da üretim ortamları için çok önemlidir.

Oluşturulan bir barkodu PDF veya PNG olarak nasıl kaydedebilirim?

IsGeneratePdfChecked özelliğini çıktı formatını belirlemek için kullanın. İşaretli ise, barkodlar PDF olarak kaydedilir; aksi takdirde, PNG resimleri olarak kaydedilir.

.NET MAUI barkod projesini iOS simülatöründe çalıştırma süreci nedir?

Projenizi kurduktan sonra Visual Studio'da hedef dağıtım olarak iOS simülatörünü seçin ve simüle edilmiş ortamda barkod işlevselliğini test etmek için projeyi çalıştırın.

.NET MAUI'de barkod tarama için örnek bir projeyi nasıl indirebilirim?

Tüm örnek proje, içindeki barkod tarama uygulama detaylarını incelemek için bir zip dosyası halinde indirilebilir ve Visual Studio'da açılabilir.

IronBarcode, barkodların toplu işlenmesini destekliyor mu?

Evet, IronBarcode toplu işlemeyi destekler, bu da geliştiricilerin büyük ölçekli uygulamalar için verimliliği artırarak tek bir işlemde birden fazla barkod oluşturmasını veya okumasını sağlar.

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında Lisans Derecesine (Carleton Üniversitesi) sahip ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirmeyle ilgileniyor. Sezgisel ve estetik açıdan hoş kullanıcı arayüzleri oluşturma tutkunu, Curtis modern çerçevelerle çalışmayı ve iyi yapı...

Daha Fazla Oku
Başlamaya Hazır mısınız?
Nuget İndirmeler 2,240,258 | Sürüm: 2026.5 just released
Still Scrolling Icon

Hâlâ Kaydırıyor Musunuz?

Hızlıca kanıt ister misiniz? PM > Install-Package BarCode
bir örnek çalıştır dizginizin barkoda dönüştüğünü izle.