NEW: Master Swift design patterns with my latest book! >>

How to scan NFC tags using Core NFC

Written by Paul Hudson    @twostraws

Any iPhones since the iPhone 7 are able to scan any NFC tags you have around, and it doesn’t take much work – iOS even provides default user interface for you.

To try it out, start by selecting your project in the project navigator, then choosing the Capabilities tab for your target. You need to enable the Near Field Communication Tag Reading capability, which configures your app to have NFC-scanning permissions.

Next, add new row to your Info.plist that completes the sentence “Hold iPhone near…”, describing your app’s usage. Open Info.plist, right-click in the white space, then choose Add Row. Select “Privacy - NFC Scan Usage Description” for the key name and “NFC tag to scan it” for the value.

That’s our configuration done, so let’s dive straight into the code. Start by opening code for your scanning view controller and adding a new import statement:

import CoreNFC

We need to start a scanning session when the app launches, but we need to store it in memory so it stays active. So, add this property to your view controller:

var session: NFCNDEFReaderSession?

Next, add these two lines of code to viewDidLoad():

session = NFCNDEFReaderSession(delegate: self, queue: DispatchQueue.main, invalidateAfterFirstRead: false)
session?.begin()

Xcode will complain that the ViewController class doesn't currently conform to the NFCNDEFReaderSessionDelegate protocol, so you'll need to amend your class definition to include it:

class ViewController: UIViewController, NFCNDEFReaderSessionDelegate {

As per usual, Xcode will then complain that you're missing some required methods, so use its recommended fix to insert these two method stubs:

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {

}

func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {

}

Both of those methods are easy enough, but error handling is particularly so – we're just going to make the error print out to the Xcode console. Fill in the didInvalidateWithError method like this:

func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
    print(error.localizedDescription)
}

Now for the didDetectNDEFs method. When this is called you'll get an array of detected messages, each of which can contain one or more records describing a single piece of data.

What you do with the NFC data is down to you, so we're just going to print it out. Modify your didDetectNDEFs method to this:

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
    for message in messages {
        for record in message.records {
            if let string = String(data: record.payload, encoding: .ascii) {
                print(string)
            }
        }
    }
}

That's all the code complete, so go ahead and run the app! If everything has worked, you will immediately see some system user interface appear prompting the user to hold their device near something to scan.

Available from iOS 11.0 – learn more in my book Practical iOS 11

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Take Swift further!

Your Swift skills let you make apps for macOS, watchOS, tvOS, and more, and for one low price you can learn it all with my Swift Platform Pack!

Click here to visit the Hacking with Swift store >>