Ionic NFC Example

Is there any example for consuming cordova nfc pulgin in ionic2 with angular2

1 Like

Ok! I have found solution.

Could you post your solution or any referances you have found please, anything would be much apreciated :slight_smile:

Follow these steps -

  1. Add phonegap-nfc
  2. import { NFC, Ndef } from ā€˜ionic-native’;
  3. Initialize NFC ( I am using Device Ready Event i.e

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

cekNFC() {
NFC.enabled()
.then(() => {
this.addListenNFC();
})
.catch(err => {
let alert = this.alertCtrl.create({
subTitle: this.translate.instant(ā€˜NFC_DISABLED_ON_NFC’),
buttons: [{ text: this.translate.instant(ā€˜OK’) }, {
text: this.translate.instant(ā€œGO_SETTINGā€),
handler: () => {
NFC.showSettings();
}
}]
});
alert.present();
});
}

addListenNFC() {
    NFC.addTagDiscoveredListener(nfcEvent => this.sesReadNFC(nfcEvent.tag)).subscribe(data => {
        if (data && data.tag && data.tag.id) {
            let tagId = NFC.bytesToHexString(data.tag.id);
            if (tagId) {
                this.nav.setRoot(PayerCard, { "TagID": tagId });
            } else {
                this.showToast(this.translate.instant('NFC_NOT_DETECTED'))
            }
        }
    });
}

sesReadNFC(data): void {
    this.showToast(this.translate.instant('NFC_WORKING'))
}

failNFC(err) {
    this.showToast('NFC Failed :' + JSON.stringify(err))
}
4 Likes

@TimmyCass , is it helpfull?

@DalbirSingh, it’s very helpful. I wonder if I have to extract the specifications of the NFC object from the examples I find on the net or if there is (somewhere) some kind of document. I find tag.id only when I read your example.

@Dalbir Can you please confirm how are you adding phonegap-nfc. I am following the tutorial over here: https://ionicframework.com/docs/native/nfc/ but it seems it’s for Angular 1 (Ionic 1). Thanks.

I am using this https://github.com/chariotsolutions/phonegap-nfc

Thanks very much for providing the resource. The moment I use

private nfc: NFC,
private ndef: Ndef

in constructor of my .ts file, the page in my app (where I am using NFC) doesn’t open. When I remove these two private parameters, everything works fine. Are you doing it some other way?

Steps are :

  1. In app.component.ts file I have imported ā€œNFC, Ndefā€ from 'ionic-native
    like
    import { StatusBar, Splashscreen, NFC, Ndef, Device } from ā€˜ionic-native’;

2.and then call following code in constructor


NFC.addTagDiscoveredListener(nfcEvent =>
this.sesReadNFC(nfcEvent.tag)).subscribe(data => {
            if (data && data.tag && data.tag.id) {
                let tagId = NFC.bytesToHexString(data.tag.id);
                if (tagId) {
                    this.showToast(tagId)
                    if (this.ApplicationService &&
this.ApplicationService.SmartCardLinking) {
                        //this.nav.setRoot(PayerPropertyLinking, { "TagID":
tagId });
                    } else {
                        //this.nav.setRoot(PayerCard, { "TagID": tagId });
                    }

                } else {

this.showToast(this.translate.instant('NFC_NOT_DETECTED'))
                }
            }
        });
2 Likes

Some how when i’m using your method addTagDiscoveredListener i couldn’t read the content that its inside the Tag and i think i only got UID of the tag. So I changed to addNdefListener and it works fine for me :slight_smile:

Here is my method:

        this.nfc.addNdefListener().subscribe(data => {
            if (data && data.tag && data.tag.id) {      
                if (data.tag.ndefMessage) {
                    let toast = this.toastCtrl.create({
                        message: 'NFC Tag found',
                        duration: 1000,
                        position: 'bottom'
                    });

                    toast.present();

                    let payload = data.tag.ndefMessage[0].payload;
                    let tagContent = this.nfc.bytesToString(payload).substring(3);
                    console.log(tagContent);
                    
                } else {
                    let toast = this.toastCtrl.create({
                        message: 'NFC Tag not found',
                        duration: 1000,
                        position: 'bottom'
                    });

                    toast.present();

                }
            }
        });

I wish that you show the code and define platform and other contents better.

I wish that you don’t talk in such an inappropriate way to users here that share their knowledge with all others here. Thank you.

I didn’t write inappropriate way. I asked politely to define some parameters and he responses to my request. Actually, I understand his answer better now and I apply his code and my NFC reader. The code is working now so big thanks to him (Dalbir).

Then this probably got lost in translation - the way you wrote it sounds not very polite.

But great that his post helped you fix your problem.

Ok. I see now. Sorry for that then. Anyway thanks.

what is sesReadNFC here ?

I am using addNdefListener() as well but i am getting ā€œnew tag collectedā€ popped out intermittently. Any clue ?

i’m stuck for weeks with NFC.

I honestly do not understand why it does not work.

I’m following your example but it does not work on my device Samsung SF Edge (NFC is Active)

Can you help me? my source…

home.ts

import { Component } from '@angular/core';
import { NavController, Platform, AlertController, ToastController } from 'ionic-angular';
import { NFC, Ndef } from '@ionic-native/nfc/ngx';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  tagId: string;

  constructor(public platform: Platform,
              private alertCtrl: AlertController, 
              private toastCtrl: ToastController,
              public navCtrl: NavController, 
              private nfc: NFC,
              private ndef: Ndef) {

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

  } 


  cekNFC() {
    this.nfc.enabled().then(() => {
      this.addListenNFC();
    })
      .catch(err => {
      let alert = this.alertCtrl.create({
      subTitle:'NFC_DISABLED_ON_NFC',
      buttons: [{ text: 'OK' }, {
      text: 'GO_SETTING',
      handler: () => {
        this.nfc.showSettings();
      }
    }]
    });

    alert.present();
    });
    }  

    addListenNFC() {
      this.nfc.addTagDiscoveredListener(nfcEvent => this.sesReadNFC(nfcEvent.tag)).subscribe(data => {
          if (data && data.tag && data.tag.id) {
              let tagId = this.nfc.bytesToHexString(data.tag.id);
              if (tagId) {
                  this.tagId= tagId;
              } else {
                  let toast = this.toastCtrl.create({
                    message: 'NFC_NOT_DETECTED',
                    duration: 2000,
                    position: 'bottom'
                  });
                  toast.present();
                  
              }
          }
      });
    }
  
  sesReadNFC(data): void {
      let toast = this.toastCtrl.create({
        message: 'NFC_WORKING',
        duration: 2000,
        position: 'bottom'
      });
      toast.present();

  }
  
  failNFC(err) {
      let toast = this.toastCtrl.create({
        message: 'NFC Failed :' + JSON.stringify(err),
        duration: 2000,
        position: 'bottom'
      });
      toast.present();      
  }


} //class

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { NFC, Ndef } from '@ionic-native/nfc/ngx';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    NFC,
    Ndef,
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

i’m getting this on console window:

nfc_error

Using anothers apps form Play Store, I can read the Tag Id from my card.

I hope you can help me.

Thanks.

Hi,

Did you get any solution for this?

Even I am getting same error

Thanks.