First time NFC read doesn't work

Hi everyone!

I have to read a NFC tag with ionic 2, the problem is the first attempt doesn’t read then if I read again is working fine,

This is my code:


@IonicPage()
@Component({
  selector: 'page-dispositivo',
  templateUrl: 'dispositivo.html',
  providers: [NFC, Ndef, Diagnostic, Vibration]
})
export class DispositivoPage {

  subscriptions: Array<Subscription> = new Array<Subscription>();

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private auth: AuthService,
    public loading: LoadingController,
    public alertCtrl: AlertController,
    public toastCtrl: ToastController,
    private nfc: NFC,
    private ndef: Ndef,
    public diagnostic: Diagnostic,
    public platform: Platform,
    public vibration: Vibration
  ) {

    platform.ready().then(() => {
      this.initNFC();
    });
  }

  initNFC() {
    this.nfc.enabled()
      .then(() => {
        this.addListenNFC();
      }).catch(err => {
        let alert = this.alertCtrl.create({
          subTitle: 'Active la conexión NFC para para leer artículos',
          buttons: [
            {
              text: 'Activar más tarde',
              handler: () => {
                this.goToHome();
              }
            },
            {
              text: 'Ir a Ajustes para activar',
              handler: () => {
                this.nfc.showSettings().then(rs => {
                  this.goToHome();
                });
              }
            }]
        });
        alert.present();
      });
  }

  addListenNFC() {
    this.subscriptions.push(this.nfc.addTagDiscoveredListener().subscribe(nfcData => {
      this.processResponse(nfcData);
    }));
  }


I don’t know what is happening, somebody can help me?

Me too. @Carlosvel60 did you found a work around?

P.

I know this is bit late but , the solution is much simpler than the problem ,
first use only single subscription dont use the array.

subscriptions:Subscription = new Subscription();
ndeflistner:any;

later in code;
this.ndeflistner = this.nfc.addMimeTypeListener(this.tpe);

u may use addndefListner() too

then subscrible to it

this.subscriptions = this.ndeflistner.subscribe(data=>{
//your code
});

Thank you for the help.

I didn’t understand what is the class “Subscription”. Where is it defined?

This is my code:

import { Component } from '@angular/core';
import { Platform, AlertController } from 'ionic-angular';
import { NFC } from '@ionic-native/nfc';
import { SplashScreen } from '@ionic-native/splash-screen';
import { InAppBrowser } from '@ionic-native/in-app-browser';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
    
    tagId: string = "??"
    timeout: any
    scrivibile: string
    proteggibile: string
    maxSize: number
    readOnly: string

    constructor(private nfc: NFC, private platform: Platform,
                private alertCtrl: AlertController, private splashScreen: SplashScreen,
                private iab: InAppBrowser) {
        platform.ready().then(() => {
            console.log('Platform ready: checking for nfc enabled...')
            this.timeout = setInterval(() => {
                this.timeoutExpired();
            }, 1000*0.5);
            console.log('Timeout started');
            nfc.enabled().then((flag) => {
                clearInterval(this.timeout);
                console.log('nfc enabled risponde: ' + flag);
                    nfc.addNdefListener().subscribe(
                        (data: Event) => this.nfcOkNdef(data),
                        (err)  => console.log(err)
                    );
                splashScreen.hide();
            });
        });

    }

    timeoutExpired() {
        this.splashScreen.hide();
        clearInterval(this.timeout);
        let noNfc = this.alertCtrl.create({
            title: 'NFC not enabled',
            message: 'App will expired; do you want NFC setup to open?',
            buttons: [
                {text: 'Yes', handler: () => { this.nfc.showSettings(); this.platform.exitApp(); } },
                {text: 'No', handler: () => { this.platform.exitApp() } }
            ]
        })
        noNfc.present();
    }

    .....some other functions.....

}

Any help will be appreciated.

use import {Subscription} from ‘rxjs/Subscription’
You need to learn the angular basics to really understand all the things .
Writing nfc service is not a cake walk .

I will give you an advice , if your using nfc tags then you can use write and ndef listner combo,
if you want to transfer data between two android devices , then android beam ,
functions to use for android beam is nfc.share and listner at other end.

Thanks a lot for helping…
I tried, but it’s the same: the first scan does not trigger the subscription. Then all run OK.
By the way, I need only the ID of the NFC. I read also the data programmed in, but this is no important. And I don’t write the nfc, anyway.

Pietro

I have implemented it , use single subscription and attached that listner to subscription , and are you reading tags of android phone

Hi friend. I need to do the same.

could you make it work?

To my case, open a post here:

Can you help me?

Best Rgs.

Hi Friend, can you share your source?

Best Rgs.

This is a test I made to try to resolve the first time read of a NFC. It works after the first readout (test on Samsung S6 and J5, Hauawei P10 lite)
It’s Ionic 3 (now I’m moving toward Ionic 4, but I didn’t test NFC up to now).

Home.ts:

import { Component } from '@angular/core';
import { Platform, AlertController } from 'ionic-angular';
import { NFC } from '@ionic-native/nfc';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Subscription } from 'rxjs/Subscription'

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
    
    tagId: string = "??"
    timeout: any
    ready = ""
    subscription: Subscription = new Subscription
    ndeflistener: any

    constructor(private nfc: NFC, private platform: Platform, private alertCtrl: AlertController,
                private splashScreen: SplashScreen) {
        platform.ready().then(() => {
            console.log('Platform ready: checking for nfc enabled...')
            this.timeout = setInterval(() => {
                this.timeoutExpired();
            }, 1000*0.5);
            console.log('Timeout started');
            nfc.enabled().then((flag) => {
                clearInterval(this.timeout);
                console.log('nfc enabled risponde: ' + flag);
                this.ascoltaNfc();
                splashScreen.hide();
                this.ready = "Ready"
            });
        });

    }

    ascoltaNfc() {
        this.ndeflistener = this.nfc.addNdefListener()
        this.subscription = this.ndeflistener.subscribe(
            (data: Event) => this.nfcOkNdef(data),
            (err)  => console.log(err)
        );
    }

    timeoutExpired() {
        this.splashScreen.hide();
        clearInterval(this.timeout);
        let noNfc = this.alertCtrl.create({
            title: 'NFC not enabled',
            message: 'App will expire; do you want NFC setup to open?',
            buttons: [
                {text: 'Yes', handler: () => { this.nfc.showSettings(); this.platform.exitApp(); } },
                {text: 'No', handler: () => { this.platform.exitApp() } }
            ]
        })
        noNfc.present();
    }

    nfcOkNdef(event) {
        this.tagId = this.nfc.bytesToHexString(event.tag.id);
        console.log(typeof(this.tagId) + " tagId: " + this.tagId);
        let alert = this.alertCtrl.create({
            title: 'Reded',
            message: "tagId: " + this.tagId,
            buttons: ["OK"]
        })
        alert.present();
    }

}







Home HTML:

<ion-header>
    <ion-toolbar color="danger">
        <ion-title>
            Bug buster
        </ion-title>
    </ion-toolbar>
</ion-header>

<ion-content>
    <div align=center><br><br>
        <h1>Scan a tag</h1>
        <br><br><br><hr><br><br><br>
        <h1> {{ready}} </h1>
    </div>
    <div>
        <br>&nbsp;&nbsp;&nbsp;{{scanned}}{{scanName}}<br>
    </div>
</ion-content>

<ion-footer>
</ion-footer>
1 Like

Thanks a lot man! I’ll try your source and let you know.

Best Rgs.