NEW: Nominations are now open for the 2019 Swift Community Awards! >>

How to scan NFC tags using Core NFC

Swift version: 5.1

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.

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

Available from iOS 11.0 – learn more in my book Advanced iOS: Volume Two

Similar solutions…

About the Swift Knowledge Base

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

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5