Sharing an Url using NFC in Windows Phone 8

I’m always looking for ways to make use of the new features available in an updated platform. So one of my apps, a Daily offer app (iBood), could have a nice Tap and Share functionality, to share the weblink to the Daily offer.

But how am I going to develop this? I still have no Windows Phone 8 device, even worse, to test this I thought two devices were needed. I’m wrong!

The app can be tested within the Windows Phone emulator which indeed supports NFC. But uh, there’s a need for another device. And there’s a solution for that as well, the Proximity Tapper!

There’s a lot of documentation on the Proximity Tapper website, but basically al I want it to do, is to virtually Tap the emulator.

Now the setup is done, let’s start coding!

Listening for near devices

I explicitly let the user start the Tap and Share functionality through the menu. I’m not sure if it would drain the battery if you start listening for devices upon App start (can anyone confirm?), but I thought it would be good if there was explicit user interaction.

You can just start listening to the DeviceArrived event, like this:

_device = ProximityDevice.GetDefault();
if (_device != null)
{
    _device.DeviceArrived += DeviceArrived;
}

 

You will need to check for a null value, because when there’s no NFC support on the device you’re running on the GetDefault method will return null.

Sending data

So when the DeviceArrived event occurs we immediately start sending data. In my case I want to share the Uri for the daily offer, but it could be anything.

There are two operations that I could use for sending the Uri: PublishUriMessage or PublishBinaryMessage.

The PublishUriMessage simply accepts an Uri instance, though behind the scenes I saw it did send also a uniquer identifier for your application. I think this operation is specially meant to share data to your own application on another device. I just wanted to send the Uri so I went ahead and used the PublishBinaryMessage.

private void DeviceArrived(ProximityDevice sender)
{
    sender.PublishBinaryMessage("WindowsUri", IboodOfTheDay.BuyUri.ToString().ToBuffer());
}

 

An NFC-message consists of a type, in this case it is a WindowsUri, and an IBuffer. So I wrote an extension method that converts a string to an IBuffer.

public static class StringExtensions
{
    public static IBuffer ToBuffer(this string str)
    {
        using (var dw = new DataWriter())
        {
            dw.UnicodeEncoding = UnicodeEncoding.Utf16LE;
            dw.WriteString(str);
            return dw.DetachBuffer();
        }
    }
}

 

So basically that’s all I did to implement NFC in my app. When you run the Proximity Tapper you can see the data coming in, so that should be right. There’s more on NFC, like the NDEF message specifications and a library which implements the specifications.

Gravatar