core-nfc
dpearson2699/swift-ios-skills
Read and write NFC tags on iPhone using CoreNFC framework.
What is core-nfc?
CoreNFC skill provides Swift APIs for scanning and writing NDEF tags, ISO7816/ISO15693/FeliCa/MIFARE tags, and managing NFC session lifecycle on iPhone 7+. Use this when building iOS apps that need to interact with physical NFC tags for reading URLs, text, MIME data, or custom payloads.
- Scan NDEF-formatted tags with NFCNDEFReaderSession
- Read ISO7816, ISO15693, FeliCa, and MIFARE tags via NFCTagReaderSession
- Write NDEF messages to read-write capable tags
- Query tag NDEF status and capacity before operations
- Handle NFC session lifecycle with proper error handling and invalidation
- Support background tag reading with configured entitlements
How to install core-nfc
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill core-nfc- Xcode project with Near Field Communication Tag Reading capability enabled
- NFCReaderUsageDescription added to Info.plist with user-facing reason string
- com.apple.developer.nfc.readersession.formats entitlement set to TAG value
- iPhone 7 or later device for testing
- For ISO7816 tags: supported AIDs in com.apple.developer.nfc.readersession.iso7816.select-identifiers
- For FeliCa tags: supported system codes in com.apple.developer.nfc.readersession.felica.systemcodes
How to use core-nfc
- 1.Check NFC availability using NFCNDEFReaderSession.readingAvailable or NFCTagReaderSession.readingAvailable before creating sessions
- 2.Create an NFCNDEFReaderSession for standard NDEF tags or NFCTagReaderSession for protocol-specific access
- 3.Set alertMessage on the session to guide users
- 4.Call session.begin() to start scanning
- 5.Implement delegate methods to handle detected tags and connection results
- 6.For read-write operations, call queryNDEFStatus to verify tag capability before writing
- 7.Use tag.readNDEF() to read messages or tag.writeNDEF() to write messages
- 8.Call session.invalidate() or session.invalidate(errorMessage:) when done or on error
Use cases
- Reading URLs or contact information from NFC tags in a retail or event app
- Writing custom NDEF payloads to tags for inventory or asset tracking
- Scanning ISO7816 tags for access control or identification systems
- Building a tag reader that supports multiple tag protocols in a single session
- Implementing background NFC detection with proper entitlements and Info.plist configuration
- iOS app developers building NFC-enabled features
- Mobile engineers working on inventory, access control, or asset tracking systems
- Developers integrating NFC tag reading into retail, event, or hospitality apps
core-nfc FAQ
NFCNDEFReaderSession reads NDEF-formatted tags (standard format for URLs, text, MIME data). NFCTagReaderSession provides direct access to native tag protocols (ISO7816, ISO15693, FeliCa, MIFARE) for lower-level operations.
Use guard NFCNDEFReaderSession.readingAvailable or guard NFCTagReaderSession.readingAvailable before creating sessions. This returns false on unsupported devices or when NFC is restricted.
No. Call queryNDEFStatus on the tag first. Only tags with .readWrite status can be written to. Read-only tags can only be read.
For ISO7816 tags, add supported AIDs to com.apple.developer.nfc.readersession.iso7816.select-identifiers in Info.plist. For FeliCa tags, add system codes to com.apple.developer.nfc.readersession.felica.systemcodes. Do not use wildcard system codes.
Implement the didInvalidateWithError delegate method. Check the NFCReaderError code to distinguish between user cancellation, first-read completion, and actual errors. Avoid showing alerts for expected invalidation codes.
Full instructions (SKILL.md)
Source of truth, from dpearson2699/swift-ios-skills.
name: core-nfc description: "Read and write NFC tags using CoreNFC. Use when scanning NDEF tags, reading ISO7816/ISO15693/FeliCa/MIFARE tags, writing NDEF messages, handling NFC session lifecycle, configuring NFC entitlements, or implementing background tag reading in iOS apps."
CoreNFC
Read and write NFC tags on iPhone using the CoreNFC framework. Covers NDEF reader sessions, tag reader sessions, NDEF message construction, entitlements, and background tag reading. Targets Swift 6.3 / iOS 26+.
Contents
- Setup
- NDEF Reader Session
- Tag Reader Session
- Writing NDEF Messages
- NDEF Payload Types
- Background Tag Reading
- Common Mistakes
- Review Checklist
- References
Setup
Project Configuration
- Add the Near Field Communication Tag Reading capability in Xcode
- Add
NFCReaderUsageDescriptionto Info.plist with a user-facing reason string - Add the
com.apple.developer.nfc.readersession.formatsentitlement with the currentTAGvalue; do not add legacyNDEF - For ISO 7816 tags, add supported application identifiers to
com.apple.developer.nfc.readersession.iso7816.select-identifiersin Info.plist - For FeliCa tags, add supported system codes to
com.apple.developer.nfc.readersession.felica.systemcodes; do not use wildcard system codes
Device Requirements
NFC reading requires iPhone 7 or later. Always check for reader session availability before creating NFC UI or sessions. Use the concrete reader session type you are about to create.
import CoreNFC
guard NFCNDEFReaderSession.readingAvailable else {
// Device does not support NFC or feature is restricted
showUnsupportedMessage()
return
}
Key Types
| Type | Role |
|---|---|
NFCNDEFReaderSession | Scans for NDEF-formatted tags |
NFCTagReaderSession | Scans for ISO7816, ISO15693, FeliCa, MIFARE tags |
NFCNDEFMessage | Collection of NDEF payload records |
NFCNDEFPayload | Single record within an NDEF message |
NFCNDEFTag | Protocol for interacting with an NDEF-capable tag |
NDEF Reader Session
Use NFCNDEFReaderSession to read NDEF-formatted data from tags. This is the
simplest path for reading standard tag content like URLs, text, and MIME data.
import CoreNFC
final class NDEFReader: NSObject, NFCNDEFReaderSessionDelegate {
private var session: NFCNDEFReaderSession?
func beginScanning() {
guard NFCNDEFReaderSession.readingAvailable else { return }
session = NFCNDEFReaderSession(
delegate: self,
queue: nil,
invalidateAfterFirstRead: false
)
session?.alertMessage = "Hold your iPhone near an NFC tag."
session?.begin()
}
// MARK: - NFCNDEFReaderSessionDelegate
func readerSessionDidBecomeActive(_ session: NFCNDEFReaderSession) {
// Session is scanning
}
func readerSession(
_ session: NFCNDEFReaderSession,
didDetectNDEFs messages: [NFCNDEFMessage]
) {
for message in messages {
for record in message.records {
processRecord(record)
}
}
}
func readerSession(
_ session: NFCNDEFReaderSession,
didInvalidateWithError error: Error
) {
let nfcError = error as? NFCReaderError
if nfcError?.code != .readerSessionInvalidationErrorFirstNDEFTagRead,
nfcError?.code != .readerSessionInvalidationErrorUserCanceled {
print("Session invalidated: \(error.localizedDescription)")
}
self.session = nil
}
}
Reading with Tag Connection
For read-write operations, use the tag-detection delegate method to connect to individual tags:
func readerSession(
_ session: NFCNDEFReaderSession,
didDetect tags: [any NFCNDEFTag]
) {
guard let tag = tags.first else {
session.restartPolling()
return
}
session.connect(to: tag) { error in
if let error {
session.invalidate(errorMessage: "Connection failed: \(error)")
return
}
tag.queryNDEFStatus { status, capacity, error in
guard error == nil else {
session.invalidate(errorMessage: "Query failed.")
return
}
switch status {
case .notSupported:
session.invalidate(errorMessage: "Tag is not NDEF compliant.")
case .readOnly:
tag.readNDEF { message, error in
if let message {
self.processMessage(message)
}
session.invalidate()
}
case .readWrite:
tag.readNDEF { message, error in
if let message {
self.processMessage(message)
}
session.alertMessage = "Tag read successfully."
session.invalidate()
}
@unknown default:
session.invalidate()
}
}
}
}
Tag Reader Session
Use NFCTagReaderSession when you need direct access to the native tag
protocol (ISO 7816, ISO 15693, FeliCa, or MIFARE).
Polling options are protocol-specific: .iso14443 detects ISO
7816-compatible and MIFARE tags, .iso15693 detects ISO 15693 tags, and
.iso18092 detects FeliCa tags. Do not use NFCTagReaderSession for
payment-related AIDs; Apple documents NFCPaymentTagReaderSession for
eligible EU payment use cases.
final class TagReader: NSObject, NFCTagReaderSessionDelegate {
private var session: NFCTagReaderSession?
func beginScanning() {
guard NFCTagReaderSession.readingAvailable else { return }
session = NFCTagReaderSession(
pollingOption: [.iso14443, .iso15693, .iso18092],
delegate: self,
queue: nil
)
session?.alertMessage = "Hold your iPhone near a tag."
session?.begin()
}
func tagReaderSessionDidBecomeActive(
_ session: NFCTagReaderSession
) { }
func tagReaderSession(
_ session: NFCTagReaderSession,
didDetect tags: [NFCTag]
) {
guard let tag = tags.first else { return }
session.connect(to: tag) { error in
guard error == nil else {
session.invalidate(
errorMessage: "Connection failed."
)
return
}
switch tag {
case .iso7816(let iso7816Tag):
self.readISO7816(tag: iso7816Tag, session: session)
case .miFare(let miFareTag):
self.readMiFare(tag: miFareTag, session: session)
case .iso15693(let iso15693Tag):
self.readISO15693(tag: iso15693Tag, session: session)
case .feliCa(let feliCaTag):
self.readFeliCa(tag: feliCaTag, session: session)
@unknown default:
session.invalidate(errorMessage: "Unsupported tag type.")
}
}
}
func tagReaderSession(
_ session: NFCTagReaderSession,
didInvalidateWithError error: Error
) {
self.session = nil
}
}
Writing NDEF Messages
Write NDEF data to a connected tag. Always check readWrite status first.
func writeToTag(
tag: any NFCNDEFTag,
session: NFCNDEFReaderSession,
url: URL
) {
tag.queryNDEFStatus { status, capacity, error in
guard status == .readWrite else {
session.invalidate(errorMessage: "Tag is read-only.")
return
}
guard let payload = NFCNDEFPayload.wellKnownTypeURIPayload(
url: url
) else {
session.invalidate(errorMessage: "Invalid URL.")
return
}
let message = NFCNDEFMessage(records: [payload])
tag.writeNDEF(message) { error in
if let error {
session.invalidate(
errorMessage: "Write failed: \(error.localizedDescription)"
)
} else {
session.alertMessage = "Tag written successfully."
session.invalidate()
}
}
}
}
NDEF Payload Types
Creating Common Payloads
// URL payload
let urlPayload = NFCNDEFPayload.wellKnownTypeURIPayload(
url: URL(string: "https://example.com")!
)
// Text payload
let textPayload = NFCNDEFPayload.wellKnownTypeTextPayload(
string: "Hello NFC",
locale: Locale(identifier: "en")
)
// Custom payload
let customPayload = NFCNDEFPayload(
format: .nfcExternal,
type: "com.example:mytype".data(using: .utf8)!,
identifier: Data(),
payload: "custom-data".data(using: .utf8)!
)
Parsing Payload Content
func processRecord(_ record: NFCNDEFPayload) {
switch record.typeNameFormat {
case .nfcWellKnown:
if let url = record.wellKnownTypeURIPayload() {
print("URL: \(url)")
} else if let (text, locale) = record.wellKnownTypeTextPayload() {
print("Text (\(locale)): \(text)")
}
case .absoluteURI:
if let uri = String(data: record.payload, encoding: .utf8) {
print("Absolute URI: \(uri)")
}
case .media:
let mimeType = String(data: record.type, encoding: .utf8) ?? ""
print("MIME type: \(mimeType), size: \(record.payload.count)")
case .nfcExternal:
let type = String(data: record.type, encoding: .utf8) ?? ""
print("External type: \(type)")
case .empty, .unknown, .unchanged:
break
@unknown default:
break
}
}
Background Tag Reading
On iPhone XS and later, iOS can read NFC tags in the background without
opening your app. The NDEF message must contain a URI record
(typeNameFormat == .nfcWellKnown, type U). If there are multiple URI
records, the system uses the first one.
For app-specific routing, write a universal link to the tag and configure the Associated Domains capability for that domain. Background tag reading also supports specific system URL schemes such as web, email, SMS, telephone, FaceTime, Maps, and HomeKit setup. It does not support custom URL schemes, and the system does not route by bundle ID or arbitrary NDEF content type.
When a user taps a compatible tag, iOS displays a notification that opens
your app. Handle the tag data via NSUserActivity:
func scene(
_ scene: UIScene,
continue userActivity: NSUserActivity
) {
guard userActivity.activityType ==
NSUserActivityTypeBrowsingWeb else { return }
let message = userActivity.ndefMessagePayload
guard message.records.first?.typeNameFormat != .empty else { return }
for record in message.records {
processRecord(record)
}
}
Common Mistakes
DON'T: Use stale or missing NFC entitlements
Without the com.apple.developer.nfc.readersession.formats entitlement,
reader sessions cannot access NFC hardware. Use the current TAG value for
Core NFC reader sessions; do not copy older examples that add NDEF.
DON'T: Skip the readingAvailable check
Creating an NFC session on an unsupported or restricted device fails before the scan UI can do useful work.
Check NFCNDEFReaderSession.readingAvailable or
NFCTagReaderSession.readingAvailable before creating the matching session.
DON'T: Ignore session invalidation errors
The session invalidates for multiple reasons. Distinguishing user cancellation from real errors prevents false error alerts.
// WRONG -- shows error when user cancels
func readerSession(
_ session: NFCNDEFReaderSession,
didInvalidateWithError error: Error
) {
showAlert("NFC Error: \(error.localizedDescription)")
}
// CORRECT -- filter expected invalidation reasons
func readerSession(
_ session: NFCNDEFReaderSession,
didInvalidateWithError error: Error
) {
let nfcError = error as? NFCReaderError
switch nfcError?.code {
case .readerSessionInvalidationErrorUserCanceled,
.readerSessionInvalidationErrorFirstNDEFTagRead:
break // Normal termination
default:
showAlert("NFC Error: \(error.localizedDescription)")
}
self.session = nil
}
DON'T: Hold a strong reference to a stale session
Once a session is invalidated, it cannot be restarted. Nil out your reference and create a new session for the next scan.
// WRONG -- reusing invalidated session
func scanAgain() {
session?.begin() // Does nothing, session is dead
}
// CORRECT -- create a new session
func scanAgain() {
session = NFCNDEFReaderSession(
delegate: self, queue: nil, invalidateAfterFirstRead: false
)
session?.begin()
}
DON'T: Write without checking tag status
Writing to a read-only tag silently fails or produces confusing errors.
// WRONG -- writes without checking status
tag.writeNDEF(message) { error in
// May fail on read-only tags
}
// CORRECT -- check status first
tag.queryNDEFStatus { status, capacity, error in
guard status == .readWrite else {
session.invalidate(errorMessage: "Tag is read-only.")
return
}
tag.writeNDEF(message) { error in
// Handle result
}
}
Review Checklist
- NFC capability added in Signing & Capabilities
-
NFCReaderUsageDescriptionset in Info.plist -
com.apple.developer.nfc.readersession.formatsentitlement usesTAG, not legacyNDEF -
NFCNDEFReaderSession.readingAvailableorNFCTagReaderSession.readingAvailablechecked before creating sessions - Session delegate set before calling
begin() - Session reference set to nil after invalidation
-
didInvalidateWithErrordistinguishes user cancellation from actual errors - NDEF status queried before write operations
- Tag capacity checked before writing large messages
- ISO 7816 application identifiers listed in Info.plist if using
NFCTagReaderSession - FeliCa system codes listed in Info.plist when polling
.iso18092 - Background tag reading uses a URI NDEF record and universal links or supported system URL schemes
- Custom URL schemes, bundle IDs, or arbitrary NDEF content types are not used for background routing
- Payment-related AIDs are routed away from
NFCTagReaderSession - Only one reader session active at a time
References
- Extended patterns (ISO 7816 commands, multi-tag scanning, NDEF locking): references/nfc-patterns.md
- Core NFC framework
- NFCNDEFReaderSession
- NFCTagReaderSession
- NFCNDEFMessage
- NFCNDEFPayload
- NFCNDEFTag
- NFCNDEFReaderSessionDelegate
- NFCTagReaderSessionDelegate
- Building an NFC Tag-Reader App
- Adding Support for Background Tag Reading
- Near Field Communication Tag Reader Session Formats Entitlement
- ISO7816 application identifiers for NFC Tag Reader Session
- ISO18092 system codes for NFC Tag Reader Session
Related skills
More from dpearson2699/swift-ios-skills and the wider catalog.

coreml
Load, configure, and run Core ML models in iOS apps with on-device inference.

cryptokit
Apple CryptoKit for Swift cryptographic primitives: hashing, encryption, signing, and key exchange.

cryptotokenkit
Access security tokens and smart cards via CryptoTokenKit for token drivers, NFC sessions, and certificate-based authentication.

debugging-instruments
Debug iOS crashes, memory leaks, and performance bottlenecks using LLDB, Memory Graph Debugger, and Instruments.

device-integrity
Verify device legitimacy and app authenticity using Apple's DeviceCheck and App Attest frameworks.

dockkit
Control motorized camera docks and enable intelligent subject tracking with DockKit for iOS.