.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!
.NET MAUI'de iOS'ta Barkod Okuma ve Yazma
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.
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.

BarCode.iOS Kütüphanesini Dahil Edin
Kütüphane çeşitli şekillerde eklenebilir. Belki de en kolay yol NuGet kullanmaktır.
- Visual Studio içinde, "Dependencies > NuGet" üzerine sağ tıklayın ve "NuGet Paketlerini Yönet..." seçeneğini seçin.
- "Gözat" sekmesini seçin ve "BarCode.iOS" arayın.
- "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:
-
Projenizin *.csproj dosyası üzerine sağ tıklayın ve "Proje Dosyasını Düzenle" seçeneğini seçin.
-
Yeni bir ItemGroup elementi oluşturun:
<ItemGroup Condition="$(TargetFramework.Contains('ios')) == true"> <PackageReference Include="BarCode.iOS" Version="2025.3.4" /> </ItemGroup>XML -
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, bunun yerine BarCode.Android kurun.
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>
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, önce barcodeInput değişkeninden değeri kontrol eder ve alır, sonra barkodu üretmek için CreateBarcode metodunu kullanır. Son olarak, Android ve 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
}
}Imports IronBarCode
Namespace IronBarcodeMauiIOS
Public Partial Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(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(sender As Object, 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(sender As Object, 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(sender As Object, 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
Using 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}" & vbCrLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End Using
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(fileData As Byte(), 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 NamespaceImports IronBarCode
Namespace IronBarcodeMauiIOS
Public Partial Class MainPage
Inherits ContentPage
Public Property IsGeneratePdfChecked As Boolean
Get
Return generatePdfCheckBox.IsChecked
End Get
Set(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(sender As Object, 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(sender As Object, 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(sender As Object, 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
Using 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}" & vbCrLf
count += 1
End Sub)
OutputText.Text = barcodeResult
End Using
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(fileData As Byte(), 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 NamespaceSon 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.
.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
BarCode.iOS paketi ne için kullanılır?
BarCode.iOS paketi, .NET çapraz platform projelerinde iOS cihazlarda barkod özelliklerini etkinleştirmek için barkod oluşturma ve tarama yetenekleri sağlar.
Projemde BarCode.iOS paketini nasıl yükleyebilirim?
BarCode.iOS paketini, Visual Studio'da NuGet Paketlerini yöneterek ve 'BarCode.iOS' aratarak NuGet kullanarak yükleyebilirsiniz. Ardından, paketi projenize ekleyin.
BarCode.iOS paketi iOS dışında başka platformlarda kullanılabilir mi?
Hayır, BarCode.iOS özel olarak iOS platformları içindir. Yalnızca iOS hedeflendiğinde dahil etmek için csproj dosyasını değiştirmelisiniz. Android için, BarCode.Android paketini kullanmalısınız.
.NET MAUI uygulamasında IronBarcode kullanarak bir barkodu nasıl oluşturabilirim?
Bir .NET MAUI uygulamasında, BarcodeWriter.CreateBarcode yöntemini kullanarak bir barkod oluşturabilir ve istenilen çıktı formatını ayarladıktan sonra SaveToDownloadsAsync yöntemi ile kaydedebilirsiniz.
.NET MAUI uygulamasında barkodları okumak için hangi yöntem kullanılır?
BarcodeReader.Read yöntemi, bir .NET MAUI uygulamasında resimlerden veya PDF dosyalarından barkodları okumak için dosya türüne bağlı olarak kullanılır.
PDF veya PNG formatında barkod oluşturma arasında nasıl geçiş yapabilirim?
Uygulamanızın ara yüzünde bir onay kutusu kullanarak çıktı formatını belirleyebilir ve ardından kodunuzda uygun olarak ToPdfBinaryData veya ToPngBinaryData yöntemlerini seçebilirsiniz.
iOS'ta IronBarcode ile bir .NET MAUI uygulaması çalıştırmak ve test etmek için hangi ortam gereklidir?
iOS'ta IronBarcode ile bir .NET MAUI uygulaması çalıştırmak ve test etmek için derleme hedefini bir iOS Simülatörü olarak değiştirmeniz ve projeyi Visual Studio üzerinden yürütmeniz gerekir.
IronBarcode'u bir .NET MAUI uygulamasında kullanırken lisans anahtarı kullanmak gerekli mi?
Evet, uygulamanızın ana sayfasında ya bir deneme ya da ücretli lisans anahtarını IronBarCode.License.LicenseKey olarak ayarlamanız gerekir.
Barkod işlemleri için uygulama arayüzünü tasarlamada XAML'nin rolü nedir?
XAML, .NET MAUI uygulama geliştirme sürecinin bir parçası olarak, barkodları oluşturmak ve okumak için düğmeler ve giriş alanları dahil olmak üzere kullanıcı arayüzünü tasarlamak için kullanılır.
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ılandırılmış, görsel olarak çekici kılavuzlar oluşturmayı seviyor.