NFC – Simple text tags on Windows Phone

This article follows on from the last post on NFC to dig a little deeper on Windows Phone and Windows 8 (both of which share the same APIs for NFC).

Requirement or just Capability

In Windows Phone you have to add the ID_CAP_PROXIMITY capability to your app to use NFC. What about the ID_REQ_NFC requirement? Well the difference here is that when you specify a requirement the app will only be made available to devices with that feature. Whether you use the requirement therefore depends on whether NFC is core to your application or is an optional feature. This means it is valid to submit an app with NFC capabilities to devices which don’t have the hardware. Therefore you must always check first if

ProximityDevice.GetDefault() == null

Types of NFC Message

So you’ve got as far as calling the SubscribeForMessage API to listen for NFC messages, if you check the help file for this function you’ll see it refers to the partner method “PublishBinaryMessage” to document the message types supported. Then you look down the list of supported protocols and your heart sinks! It’s a long list and there seems to be a lot of duplication – why when we have the NDEF standards are there Windows versions too? Which ones can I use across different platforms? Not to mention the fact that you can’t subscribe to all of these message types on Windows Phone so the utopia of a shared NFC API across both Windows APIs is shattered.

The good news is that the Windows message types are actually helpers over the top of NDEF types and are designed to simplify reading those message types, we’ll look into those on Windows 8/RT at a later stage. There is a very good NDEF library on CodePlex (and NuGet) to parse standard NDEF records. For example the way to read a plain text NDEF.Text message is actually using the NDEF message type because the API doesn’t provide a subtype specifically for Text tags. When the tag is tapped you’ll receive a message payload which you can parse with the NdefLibrary.Ndef.NdefMessage class.

private void MessageReceived(ProximityDevice device, ProximityMessage message) 

string s = System.Text.Encoding.UTF8.GetString(msg[0].Payload, 0, msg[0].Payload.Length).Substring(2);

The final thing you’ll notice from the received text is that it contains the two-character language code at the beginning. Note that there is no error checking in the above sample and it assumes that the text tag is the first record in the message. You can see from the NdefMessage class that it contains a collection of records which can be of a number of specific types. More to follow as we delve deeper…