---
name: core-nfc
description: "Core NFC on iPhone: reading and writing NDEF tags, ISO7816, ISO15693, FeliCa and MIFARE access, reader session lifecycle, NFC entitlement and Info.plist setup, background tag reading. Use when adding or reviewing NFC tag scanning or writing."
metadata:
  source: multi-agent-pipeline
---

# Core NFC

Core NFC lets an iPhone app read tags, write NDEF data and talk to a tag in its
own protocol. Everything happens inside a short-lived reader session that the
system presents as a scan sheet. Code here assumes Swift 6.3 with an iOS 26
deployment target, and only iPhone hardware reads tags.

## Project setup

1. In Signing & Capabilities, add **Near Field Communication Tag Reading**.
2. Put a sentence the user will read into `NFCReaderUsageDescription` in Info.plist.
   An empty value is a review problem.
3. The capability writes the reader-session formats entitlement
   (`...nfc.readersession.formats`) with the value `TAG`. Older samples add
   `NDEF` as well; leave that out.
4. For ISO 7816 cards, list every application identifier the app will select
   in the Info.plist select-identifiers array (shown below).
5. For FeliCa, list each system code in the Info.plist systemcodes array.
   Wildcard codes are not accepted.

```xml
<key>NFCReaderUsageDescription</key>
<string>Scanning lets you check in to the gym by tapping your member card.</string>
<key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
<array>
    <string>F0010203040506</string>
</array>
<key>com.apple.developer.nfc.readersession.felica.systemcodes</key>
<array>
    <string>12FC</string>
</array>
```

### Hardware and availability

Tag reading needs an iPhone 7 or newer. Before showing any NFC button or
creating a session, ask the session class you intend to use, for example
`NFCNDEFReaderSession.readingAvailable` or `NFCTagReaderSession.readingAvailable`.
`false` means the device lacks the hardware or NFC is restricted, so hide or
disable the feature instead of starting a session that will fail.

### Types you will meet

| Type | Role |
|------|------|
| `NFCNDEFReaderSession` | Session that scans NDEF-formatted tags |
| `NFCTagReaderSession` | Session with native access to ISO7816, ISO15693, FeliCa and MIFARE tags |
| `NFCNDEFMessage` | An NDEF message: an ordered list of records |
| `NFCNDEFPayload` | A single NDEF record |
| `NFCNDEFTag` | Protocol adopted by tags that can hold NDEF data |

## Reading NDEF data

The NDEF session is the shortest path when all you need is a URL, some text or
a MIME blob.

```swift
import CoreNFC

final class BadgeReader: NSObject, NFCNDEFReaderSessionDelegate {
    private var session: NFCNDEFReaderSession?

    func scan() {
        guard NFCNDEFReaderSession.readingAvailable else { return }
        session = NFCNDEFReaderSession(
            delegate: self,
            queue: nil,
            invalidateAfterFirstRead: false
        )
        session?.alertMessage = "Hold the top of your iPhone near the badge."
        session?.begin()
    }

    func readerSessionDidBecomeActive(_ session: NFCNDEFReaderSession) {}

    func readerSession(_ reader: NFCNDEFReaderSession, didDetectNDEFs found: [NFCNDEFMessage]) {
        for message in found {
            for record in message.records {
                handle(record)
            }
        }
    }

    func readerSession(_ reader: NFCNDEFReaderSession, didInvalidateWithError error: any Error) {
        if let nfcError = error as? NFCReaderError,
           nfcError.code == .readerSessionInvalidationErrorFirstNDEFTagRead
            || nfcError.code == .readerSessionInvalidationErrorUserCanceled {
            // Normal end of a scan, not a failure.
        } else {
            report(error)
        }
        self.session = nil
    }

    private func handle(_ record: NFCNDEFPayload) {}
    private func report(_ error: Error) {}
}
```

The first-read and user-cancel codes are ordinary endings. Only other codes
deserve an alert, and the session reference is cleared in every case.

### Connecting to the tag

To read and then write, or to inspect capacity, implement
`readerSession(_:didDetect:)` with `[any NFCNDEFTag]`. When that method exists,
the system calls it instead of `didDetectNDEFs`.

```swift
func readerSession(_ reader: NFCNDEFReaderSession, didDetect found: [any NFCNDEFTag]) {
    if found.count > 1 {
        retryAfterMultipleTags(reader)
        return
    }
    guard let first = found.first else {
        reader.restartPolling()
        return
    }
    nonisolated(unsafe) let reader = reader
    nonisolated(unsafe) let tag = first
    Task {
        do {
            try await reader.connect(to: tag)
            let (status, _) = try await tag.queryNDEFStatus()
            switch status {
            case .notSupported:
                reader.invalidate(errorMessage: "No NDEF support on this tag.")
            case .readOnly, .readWrite:
                let badge = try await tag.readNDEF()
                reader.alertMessage = "Badge read: \(badge.records.count) records."
                reader.invalidate()
            @unknown default:
                reader.invalidate(errorMessage: "Unexpected tag status.")
            }
        } catch {
            reader.invalidate(errorMessage: "Could not read the tag: \(error.localizedDescription)")
        }
    }
}
```

Every tag call also has a completion-handler form. Those handlers are
`@Sendable`, while sessions and tags are not `Sendable`, so capturing them there
draws Swift 6 warnings. The `async` forms, awaited inside one `Task`, keep the
steps in reading order, but the `Task` closure still captures the session and
the tag. Swift 6 rejects that in its region-isolation pass ("passing closure as
a 'sending' parameter risks causing data races"), so the callback hands them
over as `nonisolated(unsafe)` copies. After starting the task the callback
touches neither, which leaves the task as their only user.

An empty array means nothing usable was found yet: `restartPolling()` keeps
the sheet open and waits for the next tap.

### More than one tag in the field

Both session types can report several tags at once. Talking to one of them
while another is in range is unreliable, so do not pick one at random. Tell the
user to take the extra tags away, pause briefly so they can do it, then resume
polling on the same session:

```swift
func retryAfterMultipleTags(_ session: NFCNDEFReaderSession) {
    session.alertMessage = "More than one tag found. Remove the extras and try again."
    nonisolated(unsafe) let session = session
    Task {
        try? await Task.sleep(for: .milliseconds(500))
        session.restartPolling()
    }
}

func retryAfterMultipleTags(_ session: NFCTagReaderSession) {
    session.alertMessage = "More than one tag found. Remove the extras and try again."
    nonisolated(unsafe) let session = session
    Task {
        try? await Task.sleep(for: .milliseconds(500))
        session.restartPolling()
    }
}
```

`restartPolling()` is declared separately on each session class rather than on
the shared base, hence the two overloads. A zero-length array gets the plain
`restartPolling()` call without the message.

## Native tag access

`NFCTagReaderSession` exposes each tag family in its own protocol: ISO 7816,
ISO 15693, FeliCa and MIFARE. Pick polling options to match the tags you expect:

| Polling option | Finds |
|----------------|-------|
| `.iso14443` | ISO 7816 compatible cards and MIFARE |
| `.iso15693` | ISO 15693 vicinity tags |
| `.iso18092` | FeliCa |

Payment application identifiers are off limits for this session. For eligible
payment use cases in the EU, Apple documents a separate
`NFCPaymentTagReaderSession`.

```swift
final class CardReader: NSObject, NFCTagReaderSessionDelegate {
    private var session: NFCTagReaderSession?

    func scan() {
        guard NFCTagReaderSession.readingAvailable else { return }
        session = NFCTagReaderSession(pollingOption: [.iso14443, .iso15693], delegate: self, queue: nil)
        session?.alertMessage = "Hold your transit card near the phone."
        session?.begin()
    }

    func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) {}

    func tagReaderSession(_ reader: NFCTagReaderSession, didDetect found: [NFCTag]) {
        if found.count > 1 {
            retryAfterMultipleTags(reader)
            return
        }
        guard !found.isEmpty else {
            reader.restartPolling()
            return
        }
        nonisolated(unsafe) let reader = reader
        nonisolated(unsafe) let tags = found
        Task {
            let tag = tags[0]
            do {
                try await reader.connect(to: tag)
            } catch {
                reader.invalidate(errorMessage: error.localizedDescription)
                return
            }
            switch tag {
            case .iso7816(let card): await select(card, in: reader)
            case .miFare(let chip): await inspect(chip, in: reader)
            case .iso15693(let label): await readBlocks(label, in: reader)
            case .feliCa(let card): await readSystemCodes(card, in: reader)
            @unknown default: reader.invalidate(errorMessage: "This tag type is not handled.")
            }
        }
    }

    func tagReaderSession(_ reader: NFCTagReaderSession, didInvalidateWithError error: any Error) {
        session = nil
    }
}
```

The task receives the whole `tags` array rather than a single `NFCTag`: with
the enum value itself as the `nonisolated(unsafe)` copy, Swift 6.3 still
rejects the capture. Always connect before sending any command. The `select`, `inspect`,
`readBlocks` and `readSystemCodes` helpers stand for per-family code (APDUs,
block reads, MIFARE and FeliCa calls), which is written out in the
[patterns reference](references/nfc-patterns.md).

### Session configuration (iOS 26.4)

iOS 26.4 adds `NFCTagReaderSession.Configuration`, a value that carries the
polling options plus optional subsets of the ISO 7816 select identifiers and
FeliCa system codes from Info.plist (entries not listed there are dropped; an
empty array means all of them). `init(configuration:delegate:queue:)` builds a
session from it and, unlike `init?(pollingOption:delegate:queue:)`, is not
failable; the older initializer is deprecated as of 26.4.
`restartPolling(configuration:)` restarts discovery with a different
configuration for that one restart only: a later plain `restartPolling()` goes
back to the configuration the session was created with. The new initializer,
like the old one, is unavailable to app extensions. Keep `init?(pollingOption:delegate:queue:)` behind an
availability check while the deployment target is below 26.4.

```swift
@available(iOS 26.4, *)
func makeTransitSession(delegate: any NFCTagReaderSessionDelegate) -> NFCTagReaderSession {
    let config = NFCTagReaderSession.Configuration(
        pollingOption: [.iso14443, .iso18092],
        iso7816SelectIdentifiers: ["A000000000000001"],
        feliCaSystemCodes: []
    )
    return NFCTagReaderSession(configuration: config, delegate: delegate, queue: nil)
}

@available(iOS 26.4, *)
func pollOnlyFeliCa(_ session: NFCTagReaderSession) {
    session.restartPolling(configuration: .init(pollingOption: .iso18092))
}
```

## Writing NDEF

Query the status first. Only `.readWrite` tags accept a write; anything else
ends the session with a clear message.

```swift
func store(_ link: URL, on tag: any NFCNDEFTag, session: NFCNDEFReaderSession) async {
    do {
        let (status, _) = try await tag.queryNDEFStatus()
        guard status == .readWrite else {
            session.invalidate(errorMessage: "This tag is read-only.")
            return
        }
        guard let record = NFCNDEFPayload.wellKnownTypeURIPayload(url: link) else {
            session.invalidate(errorMessage: "Could not encode the link.")
            return
        }
        try await tag.writeNDEF(NFCNDEFMessage(records: [record]))
        session.alertMessage = "Tag updated."
        session.invalidate()
    } catch {
        session.invalidate(errorMessage: "Could not write: \(error.localizedDescription)")
    }
}
```

Check capacity against the message size before large writes; see the reference
file for the comparison and for permanent locking.

## Building and parsing payloads

| Record | Factory |
|--------|---------|
| URI | `NFCNDEFPayload.wellKnownTypeURIPayload(url:)` (optional result) |
| Text | `NFCNDEFPayload.wellKnownTypeTextPayload(string:locale:)` |
| App data | `NFCNDEFPayload(format: .nfcExternal, type:identifier:payload:)` with a `domain:type` type string |

```swift
let config = NFCNDEFPayload(
    format: .nfcExternal,
    type: Data("example.com:shelf".utf8),
    identifier: Data(),
    payload: Data(#"{"aisle":7}"#.utf8)
)
```

When reading, branch on `typeNameFormat`:

```swift
func describe(_ record: NFCNDEFPayload) -> String? {
    switch record.typeNameFormat {
    case .nfcWellKnown:
        if let url = record.wellKnownTypeURIPayload() { return url.absoluteString }
        let (text, locale) = record.wellKnownTypeTextPayload()
        return text.map { "\($0) [\(locale?.identifier ?? "?")]" }
    case .absoluteURI:
        return utf8(record.payload)
    case .media:
        return "\(utf8(record.type) ?? "unknown"), \(record.payload.count) bytes"
    case .nfcExternal:
        return utf8(record.type)
    case .empty, .unknown, .unchanged:
        return nil
    @unknown default:
        return nil
    }
}

func utf8(_ bytes: Data) -> String? { String(bytes: bytes, encoding: .utf8) }
```

## Background tag reading

iPhone XS and newer read tags without the app open. The rules:

- One record has to be a well-known URI record: `typeNameFormat` equal to
  `.nfcWellKnown` and a record type of `U`. If there are several URI records, the first one wins.
- To route to your app, write a universal link and set up Associated Domains
  for that domain.
- System schemes also work: web, mail, SMS, phone, FaceTime, Maps and HomeKit
  setup.
- Custom URL schemes do nothing here. There is no routing by bundle identifier
  or by arbitrary NDEF content type.

A matching tag posts a notification; tapping it launches the app with a
browsing-web activity:

```swift
func scene(_ scene: UIScene, continue activity: NSUserActivity) {
    guard activity.activityType == NSUserActivityTypeBrowsingWeb else { return }
    let message = activity.ndefMessagePayload
    guard let first = message.records.first, first.typeNameFormat != .empty else { return }
    for record in message.records {
        route(record)
    }
}
```

## Mistakes that keep coming back

- **Wrong or missing formats entitlement.** Without it the session cannot reach
  the NFC hardware. Use `TAG`; drop copied `NDEF` values.
- **No `readingAvailable` check.** Where NFC is missing or switched off by
  policy, session creation fails before any scan sheet appears.
- **Every invalidation treated as an error.** Cancel and first-read are normal;
  alerting on them trains users to ignore alerts.
- **Reusing a dead session.** An invalidated session cannot restart and
  `begin()` on it does nothing. Clear the reference and create a new one.
- **Writing blind.** Without a status query, writes to read-only tags fail in
  confusing ways.
- **Answering the first of several tags.** Ask the user to remove the extras
  and restart polling.

## Review checklist

- [ ] NFC Tag Reading capability is on
- [ ] `NFCReaderUsageDescription` has a real sentence
- [ ] Formats entitlement is `TAG`, with no `NDEF`
- [ ] `readingAvailable` is checked on the same session class that is created
- [ ] Delegate is supplied before `begin()`
- [ ] Session reference is cleared after invalidation
- [ ] `didInvalidateWithError` separates cancel and first-read from real errors
- [ ] Multiple detected tags lead to a remove-extras message and `restartPolling()`
- [ ] NDEF status is queried before any write
- [ ] Capacity is compared with message length before large writes
- [ ] ISO 7816 AIDs are listed when `NFCTagReaderSession` selects applications
- [ ] FeliCa system codes are listed when polling `.iso18092`
- [ ] Background tags carry a URI record with a universal link or supported system scheme
- [ ] No custom schemes, bundle IDs or content types relied on for background routing
- [ ] Payment AIDs are kept away from `NFCTagReaderSession`
- [ ] Only one reader session runs at a time

## References

- [NFC patterns](references/nfc-patterns.md): ISO 7816 APDUs, ISO 15693
  blocks, MIFARE and FeliCa commands, multi-tag handling, multi-record messages
  and capacity, tag locking, a SwiftUI scanner, error codes
- Apple documentation, all under developer.apple.com/documentation:
  - [framework overview](https://developer.apple.com/documentation/corenfc)
  - session classes: [NDEF](https://developer.apple.com/documentation/corenfc/nfcndefreadersession),
    [tag](https://developer.apple.com/documentation/corenfc/nfctagreadersession)
  - delegates: [NDEF](https://developer.apple.com/documentation/corenfc/nfcndefreadersessiondelegate),
    [tag](https://developer.apple.com/documentation/corenfc/nfctagreadersessiondelegate)
  - data types: [message](https://developer.apple.com/documentation/corenfc/nfcndefmessage),
    [payload](https://developer.apple.com/documentation/corenfc/nfcndefpayload),
    [NDEF tag protocol](https://developer.apple.com/documentation/corenfc/nfcndeftag)
  - articles: [tag-reader sample app](https://developer.apple.com/documentation/corenfc/building-an-nfc-tag-reader-app),
    [background reading](https://developer.apple.com/documentation/corenfc/adding-support-for-background-tag-reading)
  - keys: [formats entitlement](https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.developer.nfc.readersession.formats),
    [ISO 7816 AIDs](https://developer.apple.com/documentation/bundleresources/information-property-list/com.apple.developer.nfc.readersession.iso7816.select-identifiers),
    [FeliCa system codes](https://developer.apple.com/documentation/bundleresources/information-property-list/com.apple.developer.nfc.readersession.felica.systemcodes)
