V. Pivet
V. Pivet

Reputation: 1328

Ionic 2 : Use NFC

I try to create a function to do a phone vibration when a NFC card is detected. I use Ionic 2 and this : https://github.com/chariotsolutions/phonegap-nfc

I tried this way. In .ts file :

readNFCNdefListener() {
    console.log("NFC READ OK");
    NFC.addTagDiscoveredListener(onSuccess => function () {
      this.nfc_status = 'Read NdefListener';
      console.log('Read NdefListener', onSuccess);
      Vibration.vibrate([1000,250,1000]);
    });
  }

In .html file :

<ion-card>
    <ion-item (click)="readNFCNdefListener()">
      <ion-label>NFC Nef : {{this.nfc_status}}</ion-label>
    </ion-item>
  </ion-card>

It's just not effective. I don't really understand how to use this plugin. Someone can show me how to do that ?

PS : I activate NFC on my device.

I have import NFC and Ndef.

Upvotes: 2

Views: 3721

Answers (1)

You have to add some things in your config.xml :

  <platform name="android">
    <uses-permission android:name="android.permission.NFC" />
    <uses-feature android:name="android.hardware.nfc" android:required="true" />
    <intent-filter>
      <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
      <data android:mimeType="text/pg"/>
      <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
  </platform>

And if you have an xml error add this at the top of the file in widget

xmlns:android="http://schemas.android.com/apk/res/android"

for more detail about the intent-filter for android please see : https://developer.android.com/guide/topics/connectivity/nfc/nfc.html#ndef-disc

In my ts file I have :

import {NFC, Ndef} from 'ionic-native';
..
  addNfcListeners():void {
        NFC.addTagDiscoveredListener((tagEvent:Event) => this.tagListenerSuccess(tagEvent));
        NFC.addNdefListener((tagEvent:Event) => this.tagListenerSuccess(tagEvent));
    }
  tagListenerSuccess(tagEvent:Event) {
       console.log(tagEvent);
   }

Then in your logs you will see it. If you dont know how to see the logs an easy (but not the best)solution is to open android studio and you will have it on your android monitor

In my case it was :

03-02 17:31:33.712 27750-16921/com.ionicframework.tbcbyjeff820435 V/NfcPlugin: var e = document.createEvent('Events');
                                                                               e.initEvent('ndef-mime');
                                                                               e.tag = {"id":[59,12,-6,-33],"techTypes":["android.nfc.tech.NfcA","android.nfc.tech.MifareClassic","android.nfc.tech.Ndef"],"type":"com.nxp.ndef.mifareclassic","maxSize":716,"isWritable":true,"ndefMessage":[{"tnf":1,"type":[84],"id":[],"payload":[2,102,114,78,73,67,79,76]}],"canMakeReadOnly":true};

the content of your tag is in

"ndefMessage":[{"tnf":1,"type":[84],"id":[],"payload":[2,102,114,78,73,67,79,76]}]

I'm still working on decoding. Hope that's helped you

Upvotes: 2

Related Questions