iOS에서 .NET MAUI로 바코드 읽고 쓰기

This article was translated from English: Does it need improvement?
Translated
View the article in English
Ios related to iOS에서 .NET MAUI로 바코드 읽고 쓰기

.NET MAUI (멀티플랫폼 앱 UI)는 Xamarin.Forms를 기반으로 하며 .NET으로 크로스 플랫폼 애플리케이션 개발을 위한 통합 프레임워크를 제공합니다. 개발자가 Android, iOS, macOS, Windows에서 원활하게 작동하는 네이티브 사용자 인터페이스를 생성할 수 있으며, 앱 개발 프로세스를 간소화합니다.

BarCode.iOS 패키지는 iOS에 바코드 지원을 제공합니다!!

IronBarcode iOS 패키지

BarCode.iOS 패키지는 .NET 크로스 플랫폼 프로젝트를 통해 iOS 기기에서 바코드 기능을 활성화합니다. 바닐라 BarCode 패키지는 필요하지 않습니다.

Install-Package BarCode.iOS
PDF용 C# NuGet 라이브러리
### NuGet을 사용하여 설치하세요
Install-Package BarCode.iOS

.NET MAUI 프로젝트를 생성합니다.

멀티플랫폼 섹션에서 .NET MAUI 앱을 선택하고 계속합니다.

.NET MAUI 앱 프로젝트 생성

BarCode.iOS 라이브러리 포함

라이브러리는 다양한 방법으로 추가할 수 있습니다. 가장 쉬운 방법은 아마도 NuGet을 사용하는 것입니다.

  1. Visual Studio 내에서, "Dependencies > NuGet"을 우클릭하고 "Manage NuGet Packages ..."를 선택합니다.
  2. 'Browse' 탭을 선택하고 'BarCode.iOS'를 검색합니다.
  3. 'BarCode.iOS' 패키지를 선택하고 'Add Package'를 클릭합니다.

다른 플랫폼과의 문제를 방지하려면 csproj 파일을 수정하여 iOS 플랫폼을 대상으로 할 때만 패키지를 포함하도록 합니다. 이를 수행하려면:

  1. 프로젝트의 *.csproj 파일을 우클릭하고 "Edit Project File"을 선택합니다.
  2. 새로운 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>
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 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 메서드를 사용하여 바코드를 생성합니다. 마지막으로, Android와 iOS 모두에 적합한 파일을 저장하는 SaveToDownloadsAsync 메서드를 호출합니다.

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
    }
}
$vbLabelText   $csharpLabel

마지막으로, 빌드 대상을 iOS 시뮬레이터로 전환하고 프로젝트를 실행하세요.

프로젝트 실행

이것은 프로젝트를 실행하고 바코드 기능을 사용하는 방법을 보여줄 것입니다.

Execute .NET MAUI App project

.NET MAUI App 프로젝트 다운로드

이 가이드의 전체 코드를 다운로드할 수 있습니다. 이는 Visual Studio에서 .NET MAUI App 프로젝트로 열 수 있는 압축된 파일 형태로 제공됩니다.

프로젝트를 다운로드하려면 여기를 클릭하세요.

자주 묻는 질문

C#을 사용하여 iOS에서 바코드를 생성하고 스캔하는 방법은 무엇인가요?

.NET MAUI와 BarCode.iOS 패키지를 사용하면 iOS에서 바코드를 생성하고 스캔할 수 있습니다. NuGet을 통해 패키지를 설치하고 프로젝트를 설정한 다음, 제공된 메서드를 사용하여 바코드를 생성하고 읽으세요.

.NET MAUI로 바코드 스캔 앱을 개발하기 위한 필수 조건은 무엇입니까?

Visual Studio에 .NET MAUI 지원 기능이 설치되어 있고 NuGet을 통해 BarCode.iOS 패키지에 접근할 수 있는지 확인하십시오. 설치 과정에는 UI를 위한 XAML 수정과 바코드 처리를 위한 C# 코드 수정이 포함됩니다.

.NET MAUI에서 바코드 스캔 UI의 XAML 파일을 어떻게 수정해야 하나요?

XAML 파일에는 바코드 값을 입력할 필드, 바코드 작업을 위한 버튼, 결과를 표시할 레이블을 포함시키고, 레이아웃에는 VerticalStackLayoutHorizontalStackLayout 사용하십시오.

.NET MAUI 앱에서 바코드를 생성하려면 어떤 방법을 사용해야 할까요?

MainPage 클래스의 WriteBarcode 메서드를 사용하여 BarcodeWriter 클래스를 활용하고 SaveToDownloadsAsync 를 사용하여 파일을 저장함으로써 바코드를 생성합니다.

앱에서 바코드가 인식되지 않을 경우 어떻게 문제를 해결할 수 있나요?

바코드 파일이 올바르게 선택되었고 읽을 수 있는지 확인하십시오. ReadBarcode 메서드를 사용하여 바코드를 선택하고 디코딩하고, 파일 경로와 형식이 올바른지 확인하십시오.

바코드 앱에서 라이선스 키를 설정하는 목적은 무엇인가요?

앱에 라이선스 키를 설정하면 바코드 라이브러리의 모든 기능을 제한 없이 사용할 수 있으며, 이는 프로덕션 환경에 매우 중요합니다.

생성된 바코드를 PDF 또는 PNG 파일로 저장하려면 어떻게 해야 하나요?

IsGeneratePdfChecked 속성을 사용하여 출력 형식을 결정합니다. 이 속성이 선택된 경우 바코드는 PDF 파일로 저장되고, 그렇지 않은 경우 PNG 이미지로 저장됩니다.

.NET MAUI 바코드 프로젝트를 iOS 시뮬레이터에서 실행하는 과정은 무엇인가요?

프로젝트 설정을 완료한 후 Visual Studio에서 배포 대상으로 iOS 시뮬레이터를 선택하고 프로젝트를 실행하여 시뮬레이션 환경에서 바코드 기능을 테스트하십시오.

.NET MAUI에서 바코드 스캔용 샘플 프로젝트를 어떻게 다운로드할 수 있나요?

iOS에서 바코드 스캔 구현 세부 사항을 살펴보려면 Visual Studio에서 열 수 있는 완전한 샘플 프로젝트를 압축 파일로 다운로드할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.

시작할 준비 되셨나요?
Nuget 다운로드 2,108,094 | 버전: 2026.3 방금 출시되었습니다
Still Scrolling Icon

아직도 스크롤하고 계신가요?

빠른 증거를 원하시나요? PM > Install-Package BarCode
샘플을 실행하세요 실이 바코드로 변하는 모습을 지켜보세요.