×

Using NFC to exchange information

This article describes how to exchange information over Near Field Communication (NFC) between two devices, and between a device and a tag on Windows Phone 8. These two slightly different use cases are both explained in this article because on Windows Phone 8 they are implemented using the same API in a very similar way. Actually "proximity" on Windows Phone 8 is more about communication in close proximity than about any specific technology or protocol, and NFC is just one technology for the whole higher level close proximity communication.

Please notice that proximity features of Windows Phone 8 platform are not supported by the emulator, so you will need an NFC capable Windows Phone 8 device.

Getting started with device-device and device-tag communication

To get started with developing apps that interact with tags or devices using proximity messages, you need to create a Windows Phone 8 (in this case application) project and in the WMAppManifest.xml Capabilities tab specify that the application requires the ID_CAP_PROXIMITY capability. If your application is only or mostly about proximity communication, it may make sense to also select ID_REQ_NFC as a hardware requirement on the Requirements tab, so that the Marketplace does not offer the app to devices that do not have NFC hardware.

Next, add some using statements on the MainPage.xaml.cs and add an instance of Windows.Networking.Proximity.ProximityDevice as a member to your class. It is also a good idea to check if there was no proximity hardware available, and tailor the app user experience accordingly. We also have couple of member variables of type long for storing handles to active publish and subscribe operations, a member variable of type string to store a textual log, and couple of utility methods - but don't worry about this yet as this will all come together in the following sections of this article.

Out of the scope of this article are creating buttons or other UI elements in XAML and wiring the buttons to the pieces of code in this article.

...

using Windows.Networking.Proximity; // needed for the ProximityDevice
using Windows.Storage.Streams; // needed for DataReader, DataWriter

namespace MyProximityApp
{
    public partial class MainPage : PhoneApplicationPage
    {
        private ProximityDevice _device = ProximityDevice.GetDefault();
        private long _publishId = -1; // -1 is a safe default
        private long _subscribeId = -1; // -1 is a safe default
        private string _log; // we simulate a textual log here

        public MainPage()
        {
            ...

            if (_device == null)
            {
                // no proximity hardware available
            }
        }

        private void CancelPublication()
        {
            if (_publishId != -1)
            {
                _device.StopPublishingMessage(_publishId);
                _publishId = -1;
            }
        }

        private void CancelSubscription()
        {
            if (_subscribeId != -1)
            {
                _device.StopSubscribingForMessage(_subscribeId);
                _subscribeId = -1;
            }
        }

        private void ProximityDevice_MessageTransmittedHandler(ProximityDevice sender, long messageId)
        {
            _log += String.Format("Transmitted message with id {0}\n", messageId);
        }

        ...
    }
}

This is everything you need to do to start working with proximity messages.

Windows Phone 8 Proximity API

Publishing proximity messages is easy when you understand what are the available APIs on Windows Phone 8. Let's take a look at a couple of publishing methods in ProximityDevice.

  • public long PublishMessage(string messageType, string message, MessageTransmittedHandler messageTransmittedHandler)
  • public long PublishUriMessage(Uri message, MessageTransmittedHandler messageTransmittedHandler)
  • public long PublishBinaryMessage(string messageType, IBuffer message, MessageTransmittedHandler messageTransmittedHandler)
  • public void StopPublishingMessage(long messageId)

For device-to-device publish and subscribe activity you can use all of these, but with tags you need to use PublishBinaryMessage. All publishing methods return a handle of type long for the create subscription, and by using that handle with the StopPublishingMessage you can stop publishing the message. The callback delegate type is Windows.Networking.Proximity.MessageTransmittedHandler that is invoked when the published message has been transmitted to another device or written to a tag.

  • public delegate void MessageTransmittedHandler(ProximityDevice sender, long messageId)

The messageType in method signatures is a combination of protocol + subtype used to publish the message. This means that a message type for our own binary protocol could be for example Windows.urn:myproximityapp.com:mysubtype, which declares that the protocol is allowed to be what the Windows Phone 8 platform decides is best for the communication between the devices (NDEF over NFC, but possibly something else for other proximity technologies), and the type of the data transmitted is according to whatever we've specified the urn:myproximityapp.com:mysubtype data format to be. The maximum length for a subtype is 250 URI valid characters.

The following table of protocols is a simplified version of proximity protocol descriptions in MSDN. The protocol you should use in your app depends on what it is you want to transfer, while also keeping in mind that Windows Phone 8 automatically converts the non-NDEF protocols (Windows*) to NDEF when communicating over NFC. The usage of an appropriate data format in each case is a key to application interoperability over device manufacturer and operating system borders.

Protocol Targets Operations Description
Windows Between devices Publish and subscribe The message contains binary data. Message is meant to be transmitted to another device. Be very cautious when using this protocol, because for NFC transmissions Windows Phone 8 converts the subtype and data to an absolute URI NDEF (TNF 0x03) where the subtype directly becomes the value for the NDEF type which in turn is by the NDEF specification required to follow an absolute URI format. Thus, if using this, make sure that your subtype is a globally unique absolute URI according to the RFC 3986 specification.
WindowsUri Between devices Publish and subscribe The message data contains a UTF-16LE encoded string that is a URI. Transmitting the URI over NFC converts it to a Well Known Type (TNF 0x01) 'U' NDEF message.
WindowsMime Between devices Publish and subscribe The message data is of a specific mime type. For example, if the message data is a JPEG image, the message type is "WindowsMime.image/jpeg". Transmitting the data over NFC converts it to a MIME (TNF 0x02) NDEF message.
Windows:WriteTag Between device and a tag Publish only This is the same as the Windows protocol, except that the message is meant to be written to a tag.
WindowsUri:WriteTag Between device and a tag Publish only This is the same as the WindowsUri protocol, except that the message is meant to be written to a tag.
WindowsMime:WriteTag Between device and a tag Publish only This is the same as the WindowsMime protocol, except that the message is meant to be written to a tag. An example of this protocol is "WindowsMime:WriteTag.image/jpeg".
LaunchApp:WriteTag Between device and a tag Publish only Write a tag that can be used to launch a specific app with optional launch parameters. The message must be a UTF-16LE encoded string where the values are delimited by tab characters or null values in the following form: "<launch arguments>[tab]<app platform 1>[tab]<app name 1>...[tab]<app platform N>[tab]<app name N>". For Windows Phone the platform identifier is "WindowsPhone" and the app name is the Product ID. This is a Microsoft platform specific protocol.
WriteableTag Between device and a tag Subscribe only When subscribing for this message protocol, if a writeable tag is brought in to proximity, a proximity message is received that contains an 32-bit integer (little endian) indicating the maximum writeable size of the tag.
NDEF Between devices, between device and a tag Publish and subscribe The message contents are properly formatted NDEF records. The underlying type of the content for a publication using NDEF as the message type is contained in the NDEF records.
NDEF:ext Between devices, between device and a tag Subscribe only The message data is application defined NDEF records (TNF field value of 0x04).
NDEF:MIME Between devices, between device and a tag Subscribe only The message data is a properly formatted NDEF mime message (TNF field value of 0x02). For example, "NDEF:MIME.image/jpeg".
NDEF:URI Between devices, between device and a tag Subscribe only The message data is a properly formatted NDEF message of a type defined by a URI namespace (TNF field value of 0x03). This means that the data format is identified by the specified URI. An example of this protocol is "NDEF:URI.http://myproximityapp.com/sometype".
NDEF:wkt Between devices, between device and a tag Subscribe only The message data is a properly formatted NDEF message of a type defined by the NFC forum (TNF field value of 0x01). An example of this type is "NDEF:wkt.U" for the well known type of URI.
NDEF:Writetag Between device and a tag Subscribe only The message data should be written to an NFC forum standard static tag. The message data must be in a proper NDEF format.
NDEF:Unknown Between devices, between device and a tag Subscribe only The message data is an untyped NDEF message (TNF field value of 0x05).

Subscribing to proximity messages is easy. There is a method for creating a subscription in a similar way that the publishing is done, and a method to cancel a subscription. Notice that unlike publications, there can be multiple simultaneous subscriptions at a time. Windows Phone 8 handles some of the proximity message types regardless of whether a foreground application has registered for them, for example, recognized URIs schemas like "http://", but the subscribed applications will also receive the message.

  • public long SubscribeForMessage(string messageType, MessageReceivedHandler messageReceivedHandler)
  • public void StopSubscribingForMessage(long subscriptionId)

The callback delegate type for subscription is Windows.Networking.Proximity.MessageReceivedHandler.

  • public delegate void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)

Next, let's take a look at a couple of examples on how to publish and subscribe to proximity messages.

Detecting writeable tags

First, let's take a look at how you can detect when a writeable tag has entered the proximity of a device, and what the writeable size on the tag is. According to the "WriteableTag" protocol the returned message contains a 32-bit integer in little endian byte order describing the maximum writeable size of the tag.

...

namespace MyProximityApp
{
    ...

    private void SubscribeForWriteableTag()
    {
        _subscribeId = _device.SubscribeForMessage("WriteableTag",
            (ProximityDevice sender, ProximityMessage message) =>
                {
                    using (DataReader dataReader = DataReader.FromBuffer(message.Data))
                    {
                        dataReader.ByteOrder = ByteOrder.LittleEndian;

                        Int32 size = dataReader.ReadInt32();

                        _log += String.Format("Recognized a writeable tag ({0} bytes)", size);
                    }
                });
    }
}

Transmitting strings

A simple string message can be transmitted between devices simply by using the ProximityDevice's PublishMessage method. PublishMessage automatically converts the given text to UTF-8.

...

namespace MyProximityApp
{
    ...

    private void PublishStringMessageToDevice()
    {
        string text = "Hello, world!";

        _publishId = _device.PublishMessage("Windows.urn:myproximityapp.com:string", text, ProximityDevice_MessageTransmittedHandler);
    }

    private void SubscribeForStringMessage()
    {
        _subscribeId = _device.SubscribeForMessage("Windows.urn:myproximityapp.com:string",
            (ProximityDevice sender, ProximityMessage message) =>
                {
                    _log += String.Format("Received message with text \"{0}\"\n", message.DataAsString);
                });
    }
}

PublishMessage method only supports message types starting with protocol "Windows.", which means that if you want to write the string message on a tag, you need to use PublishBinaryMessage instead. Notice that we need to manually encode the text as UTF-8 to mimic the automatic encoding of PublishMessage.

...

namespace MyProximityApp
{
    ...

    private void PublishStringMessageToTag()
    {
        string text = "Hello, world!";

        using (DataWriter dataWriter = new DataWriter())
        {
            dataWriter.UnicodeEncoding = UnicodeEncoding.Utf8;
            dataWriter.WriteString(text);

            _publishId = _device.PublishBinaryMessage("Windows:WriteTag.urn:myproximityapp.com:string", dataWriter.DetachBuffer(),
                ProximityDevice_MessageTransmittedHandler);
        }
    }
}

Transmitting URIs

Publishing URI messages (web links, telephone links, application specific URI schemes, etc.) is similar to publishing string messages. You can use PublishUriMessage method to transmit to other devices, and PublishBinaryMessage to write to tags. Notice that the protocol description for "WindowsUri" requires that the URI is encoded in UTF-16LE.

...

namespace MyProximityApp
{
    ...

    private void PublishUriMessageToDevice()
    {
        Uri uri = new Uri("http://www.nokia.com");
        
        _publishId = _device.PublishUriMessage(uri, ProximityDevice_MessageTransmittedHandler);
    }

    private void PublishUriMessageToTag()
    {
        Uri uri = new Uri("http://www.nokia.com", UriKind.Absolute);

        using (DataWriter dataWriter = new DataWriter())
        {
            dataWriter.UnicodeEncoding = UnicodeEncoding.Utf16LE;
            dataWriter.WriteString(uri.ToString());
   
            _publishId = _device.PublishBinaryMessage("WindowsUri:WriteTag", dataWriter.DetachBuffer(),
                ProximityDevice_MessageTransmittedHandler);
        }
    }

    private void SubscribeForUriMessage()
    {
        _subscribeId = _device.SubscribeForMessage("WindowsUri",
            (ProximityDevice sender, ProximityMessage message) =>
                {
                    byte[] array = new byte[message.Data.Length];
                    
                    using (DataReader dataReader = DataReader.FromBuffer(message.Data))
                    {
                        dataReader.UnicodeEncoding = UnicodeEncoding.Utf16LE;
                        dataReader.ReadBytes(array);

                        Uri uri = new Uri(System.Text.Encoding.Unicode.GetString(array, 0, array.Length - 2));

                        _log += String.Format("Received URL \"{0}\"\n", uri.ToString());
                    }
                });
    }
}

Transmitting MIME typed content

You can transfer almost any data (small images, contacts, calendar events, etc.) in a feasible way by enconding it correctly and marking the data with a MIME identifier. Keep in mind when publishing large quantities of data that there is a limitation on how many bytes of data can be published with the ProximityDevice. You can check this limitation from the ProximityDevice's MaxMessageBytes property.

Here's how you could transmit a small PNG image. Notice that according to the PNG specification the byte order of data must be big endian. Notice that publishing to tag is not listed here, but the same code works otherwise, except that you need to set the message type to "WindowsMime:WriteTag.image/png" instead.

...

namespace MyProximityApp
{
    ...

    private void PublishMimeMessageToDevice()
    {
        Uri uri = new Uri("Assets/hi.png", UriKind.Relative); // a file added to project with build action "Content"

        using (Stream stream = System.Windows.Application.GetResourceStream(uri).Stream)
        {
            byte[] array = new byte[stream.Length];

            stream.Read(array, 0, (int)stream.Length);
 
            using (DataWriter dataWriter = new DataWriter())
            {
                dataWriter.ByteOrder = ByteOrder.BigEndian; // PNG specification says that data must be in MSB order
                dataWriter.WriteBytes(array);

                // to publish to a tag you would use message type "WindowsMime:WriteTag.image/png"
                _publishId = _device.PublishBinaryMessage("WindowsMime.image/png", dataWriter.DetachBuffer(),
                    ProximityDevice_MessageTransmittedHandler);
            }
        }
    }

    private void SubscribeForMimeMessage()
    {
        _subscribeId = _device.SubscribeForMessage("WindowsMime.image/png",
            (ProximityDevice sender, ProximityMessage message) =>
                {
                    byte[] array = new byte[message.Data.Length];

                    using (DataReader dataReader = DataReader.FromBuffer(message.Data))
                    {
                        dataReader.ByteOrder = ByteOrder.BigEndian; // PNG specification says that data is in MSB order
                        dataReader.ReadBytes(array);

                        Dispatcher.BeginInvoke(() => // BitmapImage must be operated on in the UI thread
                            {
                                using (MemoryStream stream = new MemoryStream(array))
                                {
                                    var bitmap = new System.Windows.Media.Imaging.BitmapImage();
                                    bitmap.SetSource(stream);

                                    // you could have the following image declared in XAML
                                    var image = new System.Windows.Controls.Image();
                                    image.Source = bitmap;
                                }
                            });

                        _log += "Received a PNG image\n";
                    }
                });
    }
}

Transmitting NDEF messages

NFC Forum has defined a binary structure for content transmissions over NFC, and this structure is called NDEF, or NFC Data Exchange Format. On top of the NDEF specification NFC Forum and other parties have defined record types (RTD, Record Type Definition) that declare how content of different kinds should be transmitted so that all NFC compliant devices understand it. NDEF or any RTDs are not in the scope of this article, but you can find the NDEF and most common RTD specifications from NFC Forum specifications.

Once you're familiar with formatting NDEF content, here's how you could transmit it between devices or write with device to a tag. This example transmits a simple URI that is formatted according to the URI RTD. Notice that publishing to tag is not listed here, but the same code works otherwise, except that you need to set the message type to "NDEF:WriteTag" instead.

...

namespace MyProximityApp
{
    ...

    private void PublishNdefMessageToDevice()
    {
        byte[] array = new byte[]
        {
            // headers

            0xD1, // MB=1, ME=1, CF=0, SR=1, TNF=WKT
            0x01, // TYPE_LENGTH=1
            0x0A, // PAYLOAD_LENGTH=10
            0x55, // TYPE='U'

            // payload

            0x01, // URI_IDENTIFIER="http://www."
            0x6E, // 'n'
            0x6F, // 'o'
            0x6B, // 'k'
            0x69, // 'i'
            0x61, // 'a'
            0x2E, // '.'
            0x63, // 'c'
            0x6F, // 'o'
            0x6D  // 'm'
        };

        using (DataWriter dataWriter = new DataWriter())
        {
            dataWriter.ByteOrder = ByteOrder.BigEndian; // NDEF specification says that data must be in MSB order
            dataWriter.WriteBytes(array);

            // to publish to a tag you would use message type "NDEF:WriteTag"
            _publishId = _device.PublishBinaryMessage("NDEF", dataWriter.DetachBuffer(),
                ProximityDevice_MessageTransmittedHandler);
        }
    }

    private void SubscribeForNdefMessage()
    {
        _subscribeId = _device.SubscribeForMessage("NDEF",
            (ProximityDevice sender, ProximityMessage message) =>
                {
                    byte[] array = new byte[message.Data.Length];

                    using (DataReader dataReader = DataReader.FromBuffer(message.Data))
                    {
                        byte[] array = new byte[message.Data.Length];

                        dataReader.ReadBytes(array);

                        // now array contains the NDEF message we published earlier
                    }

                    _log += "Received NDEF message\n"; 
                });
    }
}

Creating NDEF formatted content may be a tedious or an error prone task, but fortunately there are third party libraries available. One of these libraries is available from ndef.codeplex.com under an LGPL license. Using this library the above code could be written as follows.

...

namespace MyProximityApp
{
    ...

    private void PublishNdefMessageToDeviceUsingNdefLibrary()
    {
        var ndefUriRecord = new NdefLibrary.Ndef.NdefUriRecord();
        ndefUriRecord.Uri = "http://www.nokia.com";

        var ndefMessage = new NdefLibrary.Ndef.NdefMessage();
        ndefMessage.Add(ndefUriRecord);

        using (DataWriter dataWriter = new D+ataWriter())
        {
            dataWriter.ByteOrder = ByteOrder.BigEndian; // NDEF specification says that data must be in MSB order
            dataWriter.WriteBytes(ndefMessage.ToByteArray());

            // to publish to a tag you would use message type "NDEF:WriteTag"
            _publishId = _device.PublishBinaryMessage("NDEF", dataWriter.DetachBuffer(),
                ProximityDevice_MessageTransmittedHandler);
        }
    }

    private void SubscribeForNdefMessageUsingNdefLibrary()
    {
        _subscribeId = _device.SubscribeForMessage("NDEF",
            (ProximityDevice sender, ProximityMessage message) =>
                {
                    byte[] array = new byte[message.Data.Length];

                    using (DataReader dataReader = DataReader.FromBuffer(message.Data))
                    {
                        byte[] array = new byte[message.Data.Length];
                        dataReader.ReadBytes(array);

                        var ndefMessage = NdefLibrary.Ndef.NdefMessage.FromByteArray(array);

                        // we're naively expecting here that the record really is an URI record
                        var ndefUriRecord = new NdefLibrary.Ndef.NdefUriRecord(ndefMessage[0]);

                        _log += String.Format("Received an NDEF URI message \"{0}\"", ndefUriRecord.Uri)
                    }
                });
    }
}

Reading and parsing NDEF content has been done for example in NFC NDEF Tag Reader app.

Transmitting custom data

A common use case in applications is to transmit application domain objects between devices, and this can be achieved easily on Windows Phone. The following piece of code shows how you could transmit a custom MyShopItem object from one device to another. With just a small protocol declaration change in the PublishBinaryMessage's messageType argument the object can also be stored on a tag. When using the "Windows." protocol make sure that the subtype you declare is an absolute URI according to RFC 3986.

...

namespace MyProximityApp
{
    ...

    [System.Runtime.Serialization.DataContract]
    public class MyShopItem
    {
        [System.Runtime.Serialization.DataMember]
        public string Name { get; set; }

        [System.Runtime.Serialization.DataMember]
        public double Price { get; set; }

        [System.Runtime.Serialization.DataMember]
        public string Currency { get; set; }
    }

    private void PublishCustomBinaryMessageToDevice()
    {
        MyShopItem item = new MyShopItem()
        {
            Name = "Teddy Bear",
            Price = 19.90,
            Currency = "€"
        }

        MemoryStream stream = new MemoryStream();

        var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(MyShopItem));
        serializer.WriteObject(stream, item);

        byte[] array = new byte[stream.Length];

        stream.Position = 0;
        stream.Read(array, 0, (int)stream.Length);

        DataWriter dataWriter = new DataWriter();
        dataWriter.ByteOrder = ByteOrder.BigEndian;
        dataWriter.WriteBytes(array);

        // to publish to a tag you would use message type "Windows:WriteTag.urn:myproximityapp.com:myshopitem"
        _publishId = _device.PublishBinaryMessage("Windows.urn:myproximityapp.com:myshopitem", dataWriter.DetachBuffer(),
            ProximityDevice_MessageTransmittedHandler);
    }

    private void SubscribeForCustomBinaryMessage()
    {
        _subscribeId = _device.SubscribeForMessage("Windows.urn:myproximityapp.com:myshopitem",
            (ProximityDevice sender, ProximityMessage message) =>
                {
                    byte[] array = new byte[message.Data.Length];

                    using (DataReader dataReader = DataReader.FromBuffer(message.Data))
                    {
                        dataReader.ByteOrder = ByteOrder.BigEndian;
                        dataReader.ReadBytes(array);

                        using (MemoryStream stream = new MemoryStream(array))
                        {
                            var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(MyShopItem));

                            MyShopItem item = (MyShopItem)serializer.ReadObject(stream);

                            _log += String.Format("Received MyShopItem object ({0} {1:F2}{2})", item.Name, item.Price, item.Currency);
                        }
                    }
                });
    }
}

This kind of custom data communication has been used, for example, in Car Trumps app.

Launching applications from tags

For application launching on Windows and Windows Phone, the platform provides a dedicated protocol called "LaunchApp:WriteTag" that is applicable only for writing tags. Here's how to write a launch tag for our app, notice that the encoding for the content must be UTF-16LE.

...

namespace MyProximityApp
{
    ...

    private void PublishLaunchAppMessageToTag()
    {
        string args = "Hello, world!";
        string platform = "WindowsPhone";
        string appId = '{' + Windows.ApplicationModel.Store.CurrentApp.AppId.ToString() + '}';
        string launchAppMessage = String.Format("{0}\t{1}\t{2}", args, platform, appId);

        using (DataWriter dataWriter = new DataWriter())
        {
           dataWriter.UnicodeEncoding = UnicodeEncoding.Utf16LE;
           dataWriter.WriteString(launchAppMessage);
 
           _publishId = _device.PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer(),
               ProximityDevice_MessageTransmittedHandler);
        }
    }
}

When the tag is later read, Windows Phone 8 shows a dialog asking whether the user wants to open the app. If the app in question is not installed on the device, a dialog asking to get it from Marketplace is displayed.

If the user decides to launch the app from the dialog, our app is invoked with extra navigation parameters (here the string "Hello, world!") that can be accessed via the NavigationContext.

...

namespace MyProximityApp
{
    ...

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        string args = null;

        NavigationContext.QueryString.TryGetValue("ms_nfp_launchargs", out args);

        if (args != null)
        {
            _log += String.Format("Args from LaunchApp tag: {0}\n", args);
        }
    }
}

Sharing images with ShareMediaTask

One way to share images between devices is by using the platform's ShareMediaTask. ShareMediaTask is the generic sharing API in Windows Phone 8, and if the device that is sharing has NFC hardware, the task automatically provides a Tap+Send option for sharing images over NFC. This content sharing option is completely separate from the other sharing options explained in this article and does not need any of the previously mentioned setup. Please notice that ShareMediaTask is only able to share JPEG images and that they must reside in the media library, and that you will need to add the ID_CAP_MEDIALIB_PHOTO capability to your application to be able to access the media library.

Here's a piece of code as an example on how you could use ShareMediaTask to do simple device-to-device image sharing from your app. Notice how we need to write the image to the media library. Also keep in mind that there is no way to remove images from the media library through the MediaLibrary API, so each image that is share in this manner will also stay in the user's Saved Pictures album until manually removed in the Photos app. Also please notice that the API documentation for MediaLibrary's SavePicture method says that the data stream must be in JPEG file format.

...

namespace MyProximityApp
{
    ...

    private void PublishImageWithShareMediaTask()
    {
        Uri uri = new Uri("Assets/hi.jpg", UriKind.Relative);

        using (Stream stream = System.Windows.Application.GetResourceStream(uri).Stream)
        {
            using (var library = new Microsoft.Xna.Framework.Media.MediaLibrary())
            {
                using (var picture = library.SavePicture(DateTime.Now.Ticks.ToString(), stream))
                {
                    var task = new Microsoft.Phone.Tasks.ShareMediaTask()
                    {
                        FilePath = String.Format("C:\\Data\\Users\\Public\\Pictures\\Saved Pictures\\{0}.jpg", picture.Name)
                    };

                    task.Show();
                }
            }
        }
    }
}

Further reading

Windows Phone NFC portal on Nokia Developer Wiki contains numerous articles and code examples contributed by the developer community. For starters, you can check out for example the following articles:

NDEF Library for Proximity APIs (NFC) is an open source (LGPL) C# NDEF parsing and composing library hosted at CodePlex. It is the heart of the NFC Interactor tag reading and writing app. A number of NFC articles on the Windows Phone wiki are derived from those projects, such as:

There are also a number of proximity related code examples that you can check out, for instance:

You might also want to check out the MSDN entry Proximity for Windows Phone 8.


Last updated 4 March 2013

Back to top

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×