chariotsolutions / phonegap-nfc

PhoneGap NFC Plugin
MIT License
706 stars 557 forks source link

bytesToString returns an invalid value #242

Closed lughino closed 7 years ago

lughino commented 8 years ago

When I try to convert the payload of a tag, this comes back to me two initial additional characters en. I write in this way:

nfc.write([
      ndef.textRecord('1234'),
      ndef.textRecord('John')
      ],
      (d) => console.log('done write', d),
      (e) => console.log('errr write', e));

when I read the tag with bytesToString back to me:

nfc.bytesToString(tag.ndefMessage[0].payload) // return "en1234"
nfc.bytesToString(tag.ndefMessage[1].payload) // return "enJohn"

It is not a problem writing, in fact when I read the tag with the native reader returns the correct values!

don commented 8 years ago

You are seeing the correct behavior for an NDEF message with TNF well known, RTD text. The payload has multiple bytes prepended to the text. The first byte is the length of the language code, the next 2 bytes are the language code. Your text begins at the 4th byte.

payload = [0x02, 'e', 'n', 'J', 'o', 'h', 'n' ]

If you know all your messages have a 2 letter language code, slice the array to remove the length and language code.

nfc.bytesToString(ndefMessage[0].payload).substring(3))

A better way to do this is to check the length of the language code and remove it.

languageCodeLength = ndefMessage[0].payload[0]
nfc.bytesToString(ndefMessage[0].payload).substring(languageCodeLength +  1))