.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 (Çok platformlu Uygulama UI), çapraz platform uygulamalarını .NET ile geliştirmek için birleşik bir çerçeve sunarak Xamarin.Forms üzerine inşa edilir. Android, iOS, macOS ve Windows'da sorunsuz çalışan yerel kullanıcı arayüzleri oluşturmanıza olanak tanır ve uygulama geliştirme sürecini hızlandırır.

BarCode.iOS paketi iOS'a barkod desteği getirir!!

IronBarcode iOS Paketi

BarCode.iOS paketi, .NET çapraz platform projeleri aracılığıyla iOS cihazlarda barkod özellikleri sunar. 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

.NET MAUI Projesi Oluşturun

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

.NET MAUI App projesi oluştur

BarCode.iOS Kütüphanesini Dahil Etme

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

  1. Visual Studio içinde, "Dependencies > NuGet" üzerine sağ tıklayın ve "Manage NuGet Packages ..." seçeneğini seçin.
  2. "Browse" sekmesini seçin ve "BarCode.iOS" arayın.
  3. "BarCode.iOS" paketini seçin ve "Add Package" butonuna tıklayın.

Başka platformlarda sorunları önlemek için, csproj dosyasını yalnızca iOS platformunu hedeflediğinde paketi içerecek şekilde değiştirin. Bunu yapmak için:

  1. Projeniz için *.csproj dosyasına sağ tıklayın ve "Proje Dosyasını Düzenle"yi seçin.
  2. Aşağıdaki gibi yeni bir ItemGroup öğesi 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'un içine "BarCode.iOS" PackageReference'ını taşıyın.

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

Uygulama Arayüzünü Tasarlayın

XAML dosyasını barkodlar ve QR kodlar oluşturmak için giriş değerlerini kabul edecek şekilde değiştirin. Ayrıca, bir barkod okumak için bir belge seçmek üzere bir düğme dahil edin. Aşağıda bir örnek bulunmaktadır:

<?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ı Oku ve Yaz

Yukarıdaki MainPage.xaml kodundan, oluşturulan barkod ve QR kodunun PDF formatında olup olmayacağını belirleyebilmek için onay kutusu kullanıldığını görebiliriz. Sonraki adımda lisans anahtarını ayarlıyoruz. Bu adım için lütfen bir deneme veya ücretli lisans anahtarı kullanın.

Kod, barcodeInput değişkeninden değeri kontrol eder ve alır, ardından barkodu oluşturmak için CreateBarcode yöntemini kullanır. Son olarak, dosyayı hem Android hem de iOS için uygun şekilde kaydeden SaveToDownloadsAsync yöntemini çağırır.

iOS'ta Dosyalar uygulamasına dökümanı çıkartmak 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 olarak değiştirin ve projeyi çalıştırın.

Projeyi Çalıştır

Bu, size projeyi nasıl çalıştıracağınızı ve barkod özelliğini nasıl kullanacağınızı gösterecektir.

Execute .NET MAUI App project

.NET MAUI Uygulama Projesini İndirin

Bu rehber için tamamlanmış kodu indirebilirsiniz. Açık bir Visual Studio'da bir .NET MAUI Uygulama projesi olarak açabileceğiniz sıkıştırılmış bir dosya ile birlikte gelir.

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

Sıkça Sorulan Sorular

C# kullanarak iOS'te barkodları nasıl oluşturabilir ve tarayabilirim?

BarCode.iOS paketi ile .NET MAUI kullanarak iOS'ta barkodlar oluşturabilir ve tarayabilirsiniz. Paketi NuGet üzerinden yükleyin, projenizi ayarlayın ve barkodları oluşturmak ve okumak için sağlanan yöntemleri kullanın.

.NET MAUI'de bir barkod tarama uygulaması oluşturmak için ön koşullar nelerdir?

Visual Studio'nun .NET MAUI desteği ile yüklü olduğundan ve NuGet üzerinden BarCode.iOS paketine erişiminiz olduğundan emin olun. Kurulum, UI için XAML'yi ve barkod işlemleri için C#'ı değiştirmeyi içerecektir.

.NET MAUI'de barkod tarama UI için XAML dosyasını nasıl değiştirebilirim?

XAML dosyasında, barkod değerleri için giriş alanları, barkod işlemleri için butonlar ve sonuçları göstermek için etiketler kullanarak VerticalStackLayout ve HorizontalStackLayout ile düzen oluşturun.

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

MainPage sınıfında barkod oluşturmak için WriteBarcode yöntemini kullanın, BarcodeWriter sınıfından yararlanın ve dosyaları SaveToDownloadsAsync ile kaydedin.

Barkodum uygulamada tanınmıyorsa nasıl sorun gideririm?

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

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

Uygulamanızda bir lisans anahtarı belirlemek, barkod kütüphanesinin tüm işlevselliğinden kısıtlama olmadan yararlandığınızı garanti eder, bu da üretim ortamları için önemlidir.

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

IsGeneratePdfChecked özelliğini çıktı formatını belirlemek için kullanın. İşaretliyse, barkodlar PDF olarak kaydedilir; aksi takdirde PNG görüntüleri olarak kaydedilir.

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

Projenizi kurduktan sonra, Visual Studio'da dağıtım hedefi olarak iOS simülatörünü seçin ve simüle edilen 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?

İndirilebilir bir ziplı dosya olarak sunulan tam bir örnek proje mevcut. iOS üzerinde barkod taramanın uygulama detaylarını keşfetmek için Visual Studio'da açılabilir.

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında lisans derecesine sahiptir (Carleton Üniversitesi) ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirme üzerine uzmanlaşmıştır. Kullanıcı dostu ve estetik açıdan hoş arayüzler tasarlamaya tutkuyla bağlı olan Curtis, modern çerç...

Daha Fazlasını Oku
Başlamaya Hazır mısınız?
Nuget İndirmeler 2,169,908 | Sürüm: 2026.4 just released
Still Scrolling Icon

Hala Kaydiriyor musunuz?

Hızlı bir kanit mi istiyorsunuz? PM > Install-Package BarCode
bir örnek çalıştırın dize barkod haline geldiğini görün.