How to use the new CoreNFC API (iOs 11)

As you may have already seen, Apple’s WWDC 2017 brought its share of surprises, one of them being the new Core NFC API (for more information, we invite you to read our latest article here).

This short tutorial will take you through how to develop an iOS application that is able to read NFC tags.

Managing permissions

The first step you need to take is to enable NFC Tag Reading permissions for your App ID on the Apple Developer Center.

If you already have an app ID, you can simply edit it, or create a new one. You should finish with something like this:

Next, you need to add this new entitlement to your application’s .entitlements file. Right click on the file, select “Open As Source Code”, and add the following:

<key>com.apple.developer.nfc.readersession.formats</key>
<array>
    <string>NDEF</string>
</array>

Finally, in your Info.plist file, you need to add a new key too. Again, right click on the file, select “Open As Source Code”, and add the following:

<key>NFCReaderUsageDescription</key>
<string>your NFC tag</string>

Be careful of the text you configure in the string, because it is used by the iOS NFC tag reader.

Note that the last section of the text contains what you have just configured in the Info.plist.

That's it for permissions, you are now ready to start coding!

Using the CoreNFC API

Let's start by importing the new API module:

import CoreNFC

Then, open your ViewController, and add the following variable:

var nfcReaderSession: NFCNDEFReaderSession?

The NFCNDEFReaderSession variable is required by the API in order to start listening for NFC communications. If you pass a nil value for the queue, the NFCNDEFReaderSession will automatically create a serial dispatch queue for you.

Open your viewDidLoad() method, and initialize your object as follows:

override func viewDidLoad() {
    super.viewDidLoad()
    nfcReaderSession = NFCNDEFReaderSession.init(delegate: self, queue: nil, invalidateAfterFirstRead: false)
}

About the constructor arguments used in the example above:

  • The NFC NDEF delegate is registered on the ViewController
  • The queue is managed directly by the NFC reader, due to the ‘nil’ argument
  • After the first NDEF tag is successfully read, the session is automatically invalidated

As soon as your object is ready to use, you can call the begin() method to launch the scanner.

For instance, let’s choose to launch it through a button:

@IBAction func click(_ sender: Any) {
    nfcReaderSession!.begin()
}

Last but not least, you need to retrieve the scanning result: to do so, you need to implement the callback methods of the NFCNDEFReaderSessionDelegate.

There are two delegates to retrieve results.

The first delegate is called when there is a validation error with an NFC session:

func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
    if (error.code == 200) {
        nfcReaderSession = nil
    }
}

If the user cancels the NFC scan and closes the reader, the session is unusable. To counter this, you can update your click method, and create a new session:

@IBAction func click(_ sender: Any) {
    if (nfcReaderSession == nil) {
        nfcReaderSession = NFCNDEFReaderSession.init(delegate: self, queue: nil, invalidateAfterFirstRead: false)
    }
    nfcReaderSession!.begin()
}

The second delegate is called when an NFC activity is detected, to retrieve the appropriate content.

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs nFCNDEFMessages: [NFCNDEFMessage]) {
    for (nFCNDEFMessage) in nFCNDEFMessages {
        for (payload) in nFCNDEFMessage.records {
            let tagType = String.init(data: payload.type, encoding: .utf8)!
            print(tagType)
            let tagInformation = String.init(data: payload.payload, encoding: .utf8)!
            print(tagInformation)
        }
    }
}

You can check the content linked with your NFC tags in your Xcode logs.

Now it’s up to you to use these results in your app!

As a reminder, we are already working on an iOS NFC SDK, which will allow you to manage all of your NFC tags and their content directly in our AdTag platform.

If you are interested, and if you want your application to interact with the largest public network of beacons, get in touch with us!

Back to home