Core Nfc

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

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.

AI 產生的概覽

指導 iOS 開發者使用 Apple CoreNFC 框架讀寫 NFC 標籤。

功能
此技能提供在 iPhone 上使用 CoreNFC 的參考指引與程式碼範例,涵蓋 NDEF 讀取工作階段、針對 ISO 7816、ISO 15693、FeliCa 與 MIFARE 標籤的標籤讀取工作階段、NDEF 訊息建構與承載類型、權限與 Info.plist 設定、背景標籤讀取、常見錯誤以及審查清單。它產出的是說明性內容與 Swift 程式碼範例,而非可執行結果,並指向一份延伸模式參考檔案。
適用情境
適用於在 iOS 應用程式中實作或審查 NFC 標籤掃描、讀取或寫入,或設定 NFC 能力、權限與背景標籤讀取時。也適合排查工作階段生命週期與失效相關問題。
執行需求
不含指令碼,僅為說明與參考文件。使用所述 API 需要 Xcode、用於 NFC 讀取的 iPhone 7 或後續機型,以及「近場通訊標籤讀取」能力和相應權限與 Info.plist 用途說明。

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.

Contents

Setup

Project Configuration

  1. Add the Near Field Communication Tag Reading capability in Xcode
  2. Add NFCReaderUsageDescription to Info.plist with a user-facing reason string
  3. Add the com.apple.developer.nfc.readersession.formats entitlement with the current TAG value; do not add legacy NDEF
  4. For ISO 7816 tags, add supported application identifiers to com.apple.developer.nfc.readersession.iso7816.select-identifiers in Info.plist
  5. 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.

swift
import CoreNFC
guard NFCNDEFReaderSession.readingAvailable else {    // Device does not support NFC or feature is restricted    showUnsupportedMessage()    return}

Key Types

TypeRole
NFCNDEFReaderSessionScans for NDEF-formatted tags
NFCTagReaderSessionScans for ISO7816, ISO15693, FeliCa, MIFARE tags
NFCNDEFMessageCollection of NDEF payload records
NFCNDEFPayloadSingle record within an NDEF message
NFCNDEFTagProtocol 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.

swift
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:

swift
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 optionTags
.iso14443ISO 7816-compatible and MIFARE
.iso15693ISO 15693
.iso18092FeliCa

Do not use this session for payment-related AIDs. Load nfc-patterns.md [blocked] for protocol-specific connection, APDU, command, and response handling.

Writing NDEF Messages

Write NDEF data to a connected tag. Always check readWrite status first.

swift
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

swift
// URL payloadlet urlPayload = NFCNDEFPayload.wellKnownTypeURIPayload(    url: URL(string: "https://example.com")!)
// Text payloadlet textPayload = NFCNDEFPayload.wellKnownTypeTextPayload(    string: "Hello NFC",    locale: Locale(identifier: "en"))
// Custom payloadlet customPayload = NFCNDEFPayload(    format: .nfcExternal,    type: "com.example:mytype".data(using: .utf8)!,    identifier: Data(),    payload: "custom-data".data(using: .utf8)!)

Parsing Payload Content

Load Parsing NDEF Payload Content [blocked] for the complete type-name-format switch and multi-record handling.

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:

swift
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: Ignore session invalidation errors

The session invalidates for multiple reasons. Distinguishing user cancellation from real errors prevents false error alerts.

swift
// WRONG -- shows error when user cancelsfunc readerSession(    _ session: NFCNDEFReaderSession,    didInvalidateWithError error: Error) {    showAlert("NFC Error: \(error.localizedDescription)")}
// CORRECT -- filter expected invalidation reasonsfunc 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.

swift
// WRONG -- reusing invalidated sessionfunc scanAgain() {    session?.begin()  // Does nothing, session is dead}
// CORRECT -- create a new sessionfunc scanAgain() {    session = NFCNDEFReaderSession(        delegate: self, queue: nil, invalidateAfterFirstRead: false    )    session?.begin()}

Review Checklist

  • NFC capability added in Signing & Capabilities
  • NFCReaderUsageDescription set in Info.plist
  • com.apple.developer.nfc.readersession.formats entitlement uses TAG, not legacy NDEF
  • NFCNDEFReaderSession.readingAvailable or NFCTagReaderSession.readingAvailable checked before creating sessions
  • Session delegate set before calling begin()
  • Session reference set to nil after invalidation
  • didInvalidateWithError distinguishes 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

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/core-nfc提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新