Ionic Cordova NFC is not subscribing to or capturing events

112 views Asked by At

How can I resolve the issue in my Ionic Cordova application where it's not subscribing to the NDEF listener when using the NFC PhoneGap API

Function:

startNFCReading() {
console.log('Starting NFC reading...');

        if (!this.nfc) {
            console.log('NFC library not found');
            return;
        }

        this.nfc
            .enabled()
            .then(() => {
                console.log('NFC enabled');
                const attachListener = this.nfc.addNdefListener(
                    (event: any) => {
                        console.log('Successfully attached ndef listener');
                    },
                    (err: any) => {
                        console.log('Error attaching ndef listener', err);
                    }
                ).subscribe((event) => {
                        console.log('received ndef message. the tag contains: ', event);
                        console.log('decoded tag id', this.nfc.bytesToHexString(event.tag.id));
                        this.getProduct(event.tag.ndefMessage);
                }
                );
            })
            .catch((e) => {
                console.log('NFC not enabled', e);
                // Handle NFC not enabled error here, e.g., show a user-friendly message.
            });
        console.log('After subscription');

    }

console output

Starting NFC reading...

7239.d181bf1e42e46154a791.js:1 After subscription

7239.d181bf1e42e46154a791.js:1 NFC enabled

7239.d181bf1e42e46154a791.js:1 Successfully attached ndef listener

The console output indicates that it successfully attaches the NDEF listener, but it doesn't go to the subscribe event. I've tried debugging it, but the issue persists. What could be causing this problem, and how can I resolve it?

1

There are 1 answers

5
Matt Ellen On

Looking at the docs, you seem to need 3 functions in the addNdefListener call:

addNdefListener: function (callback, win, fail)

So I think your first function

(event: any) => {
  console.log('Successfully attached ndef listener');
}

Is being used as the callback, when you want it to be used as the win.

Try removing the subscribe call and putting that function as the callback:

const attachListener = this.nfc.addNdefListener(
  (event) => {
    console.log('received ndef message. the tag contains: ', event);
    console.log('decoded tag id', this.nfc.bytesToHexString(event.tag.id));
    this.getProduct(event.tag.ndefMessage);
  },
  () => {
    console.log('Successfully attached ndef listener');
  },
  (err: any) => {
    console.log('Error attaching ndef listener', err);
  });