Go to top button

Enhancing Your iOS App with Core NFC: A Comprehensive Guide

Alex Huang

May 31

Estimated reading time: 10 minute(s)

Enhancing Your iOS App with Core NFC: A Comprehensive Guide - Splash image

Summary


This comprehensive guide covers everything you need to know about using Core NFC in your iOS app. Discover how to read and write NFC tags, handle various NFC protocols, and implement advanced features like card emulation. Enhance your app's user experience by leveraging the power of NFC technology.

Introduction


Core NFC is a powerful framework that allows iOS developers to read and write NFC tags, providing users with more information about their physical environment and real-world objects. By integrating Core NFC into your app, you can offer users a seamless way to interact with products in stores, exhibits in museums, and much more. This guide will walk you through the basics of using Core NFC, including reading and writing NFC tags, handling various NFC protocols, and implementing advanced features.

For those new to Apple development, understanding essential frameworks is crucial. Our guide for beginner developers covers essential tools like SwiftUI, UIKit, Core Data, and more, providing a solid foundation for building robust applications.

Exploring the future of NFC in various industries can provide valuable insights. Check out our article on NFC in retail, which delves into how technologies like RFID are transforming the retail industry, with examples from companies like Uniqlo.

For more detailed information on Core NFC, visit the official Apple documentation.

Understanding Core NFC



Core NFC supports reading NFC tags of types 1 through 5 that contain data in the NFC Data Exchange Format (NDEF). It also allows writing data to tags and interacting with protocol-specific tags such as ISO 7816, ISO 15693, FeliCa™, and MIFARE®. Core NFC is available on devices that support Near Field Communication and cannot be used in app extensions.

Benefits of Using Core NFC



Enhanced User Experience



NFC technology facilitates smooth and quick interactions. Whether it's pairing devices, accessing information with a tap, or making secure payments, NFC provides a frictionless experience that can significantly enhance user satisfaction.

Versatility in Applications



From mobile payments to smart homes, Core NFC can be utilized in a variety of applications. Developers can create innovative solutions for ticketing systems, inventory management, access control, and more. The possibilities are vast, limited only by the creativity of the developer.

Security and Convenience



NFC technology is inherently secure due to its short range, reducing the risk of unauthorized access. It also adds convenience by enabling actions like unlocking doors or initiating payments without the need for physical contact, which is especially relevant in today's health-conscious environment.

Setting Up Your Project



To get started with Core NFC, you need to enable NFC capabilities in your Xcode project:

1. Open your project in Xcode.
2. Go to your app's target settings.
3. Select the "Capabilities" tab.
4. Toggle the switch for "Near Field Communication Tag Reading."

This step adds the NFC tag-reading feature to your App ID and the Near Field Communication Tag Reader Session Formats Entitlement to the entitlements file.

Next, add the NFCReaderUsageDescription key to your Info.plist file. This string should describe why your app needs access to the device’s NFC reader.

Starting a Reader Session



To start reading NFC tags, create an NFCNDEFReaderSession object. Here’s how to configure and start a reader session:

import CoreNFC

class ViewController: UIViewController, NFCNDEFReaderSessionDelegate {
var session: NFCNDEFReaderSession?

@IBAction func beginScanning(_ sender: Any) {
guard NFCNDEFReaderSession.readingAvailable else {
let alertController = UIAlertController(
title: "Scanning Not Supported",
message: "This device doesn't support tag scanning.",
preferredStyle: .alert
)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
return
}

session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
session?.alertMessage = "Hold your iPhone near the item to learn more about it."
session?.begin()
}

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

func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
print("NFC Session Invalidated: \(error.localizedDescription)")
}
}


Writing to NFC Tags



To write data to NFC tags, start a new reader session and configure it to allow writing. Here's how you can do it:

@IBAction func beginWrite(_ sender: Any) {
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
session?.alertMessage = "Hold your iPhone near an NDEF tag to write the message."
session?.begin()
}

func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCNDEFTag]) {
if tags.count > 1 {
let retryInterval = DispatchTimeInterval.milliseconds(500)
session.alertMessage = "More than 1 tag is detected. Please remove all tags and try again."
DispatchQueue.global().asyncAfter(deadline: .now() + retryInterval) {
session.restartPolling()
}
return
}

let tag = tags.first!
session.connect(to: tag) { (error: Error?) in
if let error = error {
session.alertMessage = "Unable to connect to tag."
session.invalidate()
return
}

tag.queryNDEFStatus { (ndefStatus, capacity, error) in
if let error = error {
session.alertMessage = "Unable to query the NDEF status of tag."
session.invalidate()
return
}

switch ndefStatus {
case .notSupported:
session.alertMessage = "Tag is not NDEF compliant."
session.invalidate()
case .readOnly:
session.alertMessage = "Tag is read only."
session.invalidate()
case .readWrite:
let payload = NFCNDEFPayload.wellKnownTypeTextPayload(string: "Hello, NFC!", locale: Locale(identifier: "en"))
let message = NFCNDEFMessage(records: [payload!])
tag.writeNDEF(message) { (error: Error?) in
if let error = error {
session.alertMessage = "Write NDEF message failed: \(error)"
} else {
session.alertMessage = "Write NDEF message successful."
}
session.invalidate()
}
@unknown default:
session.alertMessage = "Unknown NDEF tag status."
session.invalidate()
}
}
}
}


Handling Advanced NFC Use Cases



Core NFC also allows interaction with protocol-specific tags, enhancing the versatility of your app. Here's how you can work with some of these protocols:

ISO 7816 and ISO 15693 Tags



To interact with ISO 7816 and ISO 15693 tags, you need to use the NFCTagReaderSession class. This session type allows you to send and receive data from these tags, enabling advanced use cases like secure element communication.

import CoreNFC

func startISO7816Session() {
let session = NFCTagReaderSession(pollingOption: .iso14443, delegate: self)
session?.alertMessage = "Hold your iPhone near the ISO 7816 tag."
session?.begin()
}

func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
if let firstTag = tags.first {
session.connect(to: firstTag) { error in
if let error = error {
session.invalidate(errorMessage: "Connection failed: \(error.localizedDescription)")
return
}

if case let .iso7816(tag) = firstTag {
// Perform ISO 7816 specific operations
}
}
}
}


FeliCa™ and MIFARE® Tags



Similarly, you can interact with FeliCa™ and MIFARE® tags using the NFCTagReaderSession. These tags are commonly used in transportation systems and access control.

func startMIFARESession() {
let session = NFCTagReaderSession(pollingOption: .iso14443, delegate: self)
session?.alertMessage = "Hold your iPhone near the MIFARE tag."
session?.begin()
}

func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
if let firstTag = tags.first {
session.connect(to: firstTag) { error in
if let error = error {
session.invalidate(errorMessage: "Connection failed: \(error.localizedDescription)")
return
}

if case let .miFare(tag) = firstTag {
// Perform MIFARE specific operations
}
}
}
}


Best Practices



1. User Privacy and Security:
Always inform users when NFC scanning is active and explain how their data will be used. Implement robust security measures to protect sensitive information.

2. Optimized User Interface:
Design intuitive UI elements that guide users through the NFC scanning process. Clear instructions and feedback can enhance the user experience.

3. Thorough Testing:
Test NFC interactions across different devices and scenarios to ensure the accuracy and reliability of data read from or written to NFC tags.

Advanced Features with Core NFC



Card Emulation



With the introduction of iOS 17.4, you can now perform card emulation using the CardSession class. This allows your app to emulate a card and interact with external NFC readers.

import CoreNFC

func CardSessionSample() {
let ProcessAPDU: (_: Data) -> Data = { capdu in return Data() }

Task() {
guard NFCReaderSession.readingAvailable, CardSession.isSupported, await CardSession.isEligible else {
return
}

var presentmentIntent: NFCPresentmentIntentAssertion?
let cardSession: CardSession
do {
presentmentIntent = try await NFCPresentmentIntentAssertion.acquire()
cardSession = try await CardSession()
} catch {
return
}

for try await event in cardSession.eventStream {
switch event {
case .sessionStarted:
cardSession.alertMessage = "Communicating with card reader."
case .readerDetected:
try await cardSession.startEmulation()
case .readerDeselected:
await cardSession.stopEmulation(status: .success)
case .received(let cardAPDU):
do {
let responseAPDU = ProcessAPDU(cardAPDU.payload)
try await cardAPDU.respond(response: responseAPDU)
} catch {
// Handle the error
}
case .sessionInvalidated(reason: _):
cardSession.alertMessage = "Ending communication with card reader."
}
}

presentmentIntent = nil
}
}


Conclusion



Integrating Core NFC into your iOS app can significantly enhance the user experience by providing seamless interactions with real-world objects. Whether you're developing applications for retail, museums, or smart homes, Core NFC offers a versatile and secure solution for leveraging NFC technology. Start experimenting with Core NFC today and unlock the potential of contactless interactions in your iOS applications.

By following this guide, you'll be well-equipped to implement Core NFC in your iOS apps, providing users with innovative and engaging experiences. Leverage the power of NFC to create unique, user-friendly applications that stand out in today's competitive market.

For those new to Apple development, understanding essential frameworks is crucial. Our guide for beginner developers covers essential tools like SwiftUI, UIKit, Core Data, and more, providing a solid foundation for building robust applications.

Exploring the future of NFC in various industries can provide valuable insights. Check out our article on NFC in retail, which delves into how technologies like RFID are transforming the retail industry, with examples from companies like Uniqlo.

For more detailed information on Core NFC, visit the official Apple documentation.

Let's Connect!

I'm always excited to discuss new opportunities, innovative projects, and collaboration possibilities. Feel free to reach out through email or connect with me on  LinkedIn.

Alex Huang's Logo

Alex Huang

© 2024 Alex Huang. All Rights Reserved.