Scanner – Xamarin.Forms

Olá, neste post irei demonstrar como criar um scanner de barcode em aplicações Xamarin.Forms. Com esse scanner será possível ler os seguintes tipos de códigos:

  • Aztec
  • Code 128
  • Code 39
  • Code 93
  • EAN13
  • EAN8
  • PDF417
  • QR
  • UPC-E

ADICIONANDO O NUGET PACKAGE

Clique com o botão direito em cima de sua Solution e selecione “Manage NuGet Packages for Solution…”

1.1

 

Digite “Zxing.Net.Mobile” e selecione o plugin como demonstrado na imagem a seguir.

1

 

Selecione todos os projetos e clique no botão “Install”.

3

Xaml

Crie um botão para acionar o scanner, na propriedade “Clicked” adicione uma chamada para o método “OpenScanner”.


<ContentPage.Content>
<StackLayout>
<Button Text="Open Scanner" Clicked="OpenScanner"/>
</StackLayout>
</ContentPage.Content>

view raw

Scanner.xaml

hosted with ❤ by GitHub

CODE-BEHIND

Crie o método “Scanner” que será chamado pelo método “OpenScanner”.

No método “Scanner” crie uma ZXingScannerPage, que será responsável por realizar a leitura do barcode, assim que obtiver um resultado irá parar de escanear e demonstra-lo em um DisplayAlert.


private void OpenScanner(object sender, EventArgs e)
{
Scanner();
}
public async void Scanner()
{
var ScannerPage = new ZXingScannerPage();
ScannerPage.OnScanResult += (result) => {
// Parar de escanear
ScannerPage.IsScanning = false;
// Alert com o código escaneado
Device.BeginInvokeOnMainThread(() => {
Navigation.PopAsync();
DisplayAlert("Código escaneado", result.Text, "OK");
});
};
await Navigation.PushAsync(ScannerPage);
}

view raw

Scanner.xaml.cs

hosted with ❤ by GitHub

CONFIGURAÇÕES DA PLATAFORMA

É necessário realizar algumas configurações de acordo com cada plataforma, para definir permissões e etc…

Android

Edite o manifesto para adicionar algumas permissões, para isso clique com o botão direito no projeto .android e selecione Properties.

4

 

No Android Manifest selecione “CAMERA”, assim terá permissão para acionar a câmera do dispositivo.

permissions

MainActivity.cs

No arquivo MainActivity sobrescreva o método “OnRequestPermissionsResult” como demonstrado a seguir.


public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

view raw

MainActivity.cs

hosted with ❤ by GitHub

iOS

Adicionar permissões para que o seu app acesse a câmera na plataforma iOS é necessário editar o arquivo Info.plist que encontra-se no seu projeto .iOS

5

 

No arquivo Info.plist adicione a chave NSCameraUsageDescription como demonstrado a seguir.


</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>NSCameraUsageDescription</key>
<string>This app needs to access a camera to scan the barcode.</string>
</dict>
</plist>

view raw

Info.plist

hosted with ❤ by GitHub

AppDelegate.cs

No arquivo AppDelegate inicialize o ZXing adicionando a linha de código demonstrada a seguir dentro do método FinishedLaunching.


public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
//Inicializa o Zxing no iOS
ZXing.Net.Mobile.Forms.iOS.Platform.Init();
return base.FinishedLaunching(app, options);
}

view raw

AppDelegate.cs

hosted with ❤ by GitHub

Resultado

ezgif.com-gif-maker

 

 

Esse e todos os exemplos deste blog encontram-se disponíveis no GitHub.

icongithub

28 comentários em “Scanner – Xamarin.Forms

  1. Juliano, talvez para facilitar os usuário que irão ler esse post, deixo registrado que para funcionar esse exemplo, é necessário que o App seja baseado em uma NavigationPage. Informá-lo na classe App.

    ex:
    MainPage = new NavigationPage(new BarcodeScanner.MainPage());

    Curtir

  2. Hi,
    I’m new on mobile programming,
    my question will be obvious to you…
    I would like to change your QR-Code-Scanner-Xamarin.Forms sample,
    I need to add a textbox to main page,
    and the barcode instead of being displayed in a popup it is put in the textbox.
    Can you help me ?

    Curtir

    1. Hi Mark,

      Yes I can 😀
      First, create a Entry in your page:

      After, in your method scanner use:

      Device.BeginInvokeOnMainThread(() => {
      Navigation.PopAsync();

      yourEntry.Text = result.Text;
      });

      Hope this helps.

      Curtir

  3. hy. Thanx for article. But I get error after installing ZXing: “Package ‘ZXing.Net.Mobile 2.3.2’ was restored using ‘.NETFramework,Version=v4.6.1’ instead of the project target framework ‘.NETStandard,Version=v2.0’. This package may not be fully compatible with your project. ” I look at propreties and it does targets to v2.0. Then why do project is being created as .NET4.6, but restores as v2.0 instead ? what is the point? confusing.. Btw, I got errors after trying to “Live Run”: 1. The name ‘ZXing’ does not exist in the current context.2. The type or namespace name ‘ZXing’ could not be found .3. The type or namespace name ‘ZXingScannerPage’ could not be found. Each error suggest to check if I may be missing directives or assemblies though instelisense works very well and project builds up without errors. Error arrise when trying to run. Hope to hear from you. Thanx.

    Curtir

    1. Hello Ramin,
      Thanks, i’m happy in see that my posts its help you.

      Try use ScannerPage.ToggleTorch(); but i think not have button for ZXingScannerPage.

      I hope help you.
      Merry Christmas.

      Curtir

  4. Hi,

    I am working based on your tutorial..
    In project i am using pcl , not shared project

    I got the warning like
    Package ‘ZXing.Net.Mobile 2.3.2’ was restored using ‘.NETFramework,Version=v4.6.1’ instead of the project target framework ‘.NETStandard,Version=v2.0’. This package may not be fully compatible with your project.

    Please help me..
    How Can I solve this.

    Curtir

    1. Hi Siva,

      In the moment this nuget package show warning, but this work normally.

      I believe that in the future this nuget to be update.

      Curtir

    1. Obrigado Joilson 🙂
      Fico feliz em saber disso, me formei pela FATEC de Sorocaba.

      Se precisarem de alguma palestra ai na FATEC ZL me coloco a disposição.

      Abraço

      Curtir

  5. Hi Juliano,
    Thanks for your post and sample. I was looking for QR-Code scanner for Xamarin and ended up here.
    When I clone your repo and run, it works perfectly fine but when I start a new project and follow every steps as you said I got an error when I run it at
    LoadApplication(new App());
    in MainActivity in my Android project.

    Error :
    Unhandled Exception:
    System.NullReferenceException: Object reference not set to an instance of an object. occurred

    Im using
    Visual Studio Community 2017 Version 15.5.7
    Windows 10
    Google Nexus 5 connected via cable

    I noticed you have a package “FastAndroidCamera” but you didnt mention in your steps.
    I even tried installing same Xamarin version you have 2.3.4.270 but it didnt help.

    Any Idea? Can you please help me?

    Thanks in advance
    Hovik

    Curtir

    1. hey Juliano, Sorry it did a small mistake that caused that error. Works fine now.
      Thanks for sample again.
      Keep going…

      Curtir

  6. Bom dia Juliano, estou testando com um tablet Android 4.4, e a leitura não é realizada, testei em outro celular Samsung e a leitura é realizada com muito custo, demora um pouco, há algum ajuste que posso realizar no código para melhorar a efetividade da leitura?

    Curtir

    1. Olá Adriano, tudo bem ?
      Você já testou com outro código, as vezes o problema pode ser a qualidade do código que você está utilizando.
      Espero ter ajudado.

      Curtir

  7. Excelente Tutorial Juliano !!! Uma dúvida ! Gostaria de saber se tem como Customizar a ScanPage, tirando essa linha vermelha e colocando um quadrado com bordas na cor verde-limão . Existe essa possibilidade de Customizar o Zxing ?

    Curtir

  8. Olá, Juliano. Gostaria de implementar código de barras para um carteirinha virtual e gerar boleto, que estou fazendo em xamarin forms, pode me dar alguma dica.

    Curtir

    1. Para ler o código de barras, este exemplo do Scanner resolve o seu problema. Para gerar boletos, eu particularmente recomendaria realizar a geração do boleto do lado do servidor. Dê uma olhada no plugin BoletoNet. https://github.com/BoletoNet

      Curtir

      1. Sim.. este artigo serve também para códigos de barra. A parte do boleto não conheço nenhum até o momento.

        Curtir

Deixe um comentário