NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How to scan NFC tags using Core NFC

Swift version: 5.2

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.

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Ever ask for help and your reviewer immediately notices issues you missed? Fernando Olivares is a 10-year veteran from Big Nerd Ranch and Lambda School who can help hone your app building skills, and he's just launched a new book that does just that – use the code "hacking" to save $5!

Buy the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 3.9/5

Link copied to your pasteboard.