Skip to content
advanced Phase 8 · Media & Hardware

Core NFC

Read NFC tags and implement NFC-based features like transit cards and product authentication.

40m
2 problems
Topic Progress 0%

NFC Basics

Enabling NFC in Your App

NFC reading requires adding the NFC Tag Reading entitlement and the NFCReaderUsageDescription key to your Info.plist.

  1. Enable NFC Tag Reading capability in Xcode
  2. Add NFCReaderUsageDescription to Info.plist

NFC Capabilities on iOS

iOS supports reading NFC tags in the following formats:

  • NDEF (NFC Data Exchange Format)
  • ISO 7816
  • ISO 15693
  • FeliCa
  • MIFARE

Core NFC Framework

Import CoreNFC to access NFC reading APIs.

import CoreNFC

class NFCHandler: NSObject, NFCNDEFReaderSessionDelegate {
    var session: NFCNDEFReaderSession?
    
    func beginScanning() {
        guard NFCNDEFReaderSession.readingAvailable else {
            print("NFC not available on this device")
            return
        }
        session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
        session?.alertMessage = "Hold your iPhone near an NFC tag."
        session?.begin()
    }
    
    func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCTag]) {
        // Handle detected tags
    }
    
    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        print("Session invalidated: \(error.localizedDescription)")
    }
}

Reading NFC Tags

NFCNDEFReaderSession

Read NDEF-formatted tags which are the most common NFC tag type.

import CoreNFC

class NDEFReader: NSObject, NFCNDEFReaderSessionDelegate {
    var onMessageRead: ((NFCNDEFMessage) -> Void)?
    
    func scan() {
        let session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
        session?.alertMessage = "Scan an NFC tag"
        session?.begin()
    }
    
    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        for message in messages {
            for record in message.records {
                processRecord(record)
            }
        }
    }
    
    func processRecord(_ record: NFCNDEFPayload) {
        let type = record.type
        let payload = record.payload
        let decoded = String(data: payload, encoding: .utf8) ?? ""
        
        print("Type: \(type)")
        print("Payload: \(decoded)")
        
        // Parse well-known types
        if record.typeNameFormat == .nfcWellKnown {
            if let uri = record.wellKnownTypeURIPayload() {
                print("URI: \(uri.absoluteString)")
            }
            if let text = record.wellKnownTypeTextPayload(nil, nil) {
                print("Text: \(text)")
            }
        }
    }
}

Parsing NDEF Records

NDEF records contain typed data payloads. Common types include:

  • Text: UTF-8 encoded text with language code
  • URI: Web links, phone numbers, emails
  • Smart Poster: Combined URI with title and icon
func parseNDEFPayload(_ payload: NFCNDEFPayload) -> NDEFData {
    guard payload.typeNameFormat == .nfcWellKnown else {
        return .unknown(payload)
    }
    
    // Check for URI record
    if let uri = payload.wellKnownTypeURIPayload() {
        return .uri(uri)
    }
    
    // Check for text record
    if let (text, language) = payload.wellKnownTypeTextPayload(nil, nil) {
        return .text(text: text, language: language ?? "en")
    }
    
    return .unknown(payload)
}

enum NDEFData {
    case uri(URL)
    case text(text: String, language: String)
    case unknown(NFCNDEFPayload)
}

NFC Use Cases

Common NFC Applications

NFC technology enables various use cases in iOS apps:

  • Contactless payments - Apple Pay integration
  • Asset tracking - Tag equipment and inventory
  • Smart posters - Interactive marketing materials
  • Authentication - Access control and verification
  • Product information - Link to digital content

Reading Specific Tag Types

CoreNFC supports reading different NFC standards.

import CoreNFC

class TagReader: NSObject, NFCTagReaderSessionDelegate {
    func scanForISO7816() {
        let session = NFCTagReaderSession(pollingOption: .iso14443, delegate: self)
        session?.alertMessage = "Hold near an ISO 14443 tag"
        session?.begin()
    }
    
    func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
        guard let tag = tags.first else { return }
        
        switch tag {
        case .iso7816(let iso7816Tag):
            // Read ISO 7816 tag data
            print("ISO 7816 tag detected")
        case .miFare(let miFareTag):
            // Read MIFARE tag data
            print("MIFARE tag detected")
        case .iso15693(let iso15693Tag):
            // Read ISO 15693 tag data
            print("ISO 15693 tag detected")
        case .feliCa(let feliCaTag):
            // Read FeliCa tag data
            print("FeliCa tag detected")
        @unknown default:
            break
        }
    }
}

Best Practices

  • Always check NFCNDEFReaderSession.readingAvailable before scanning
  • Provide clear user feedback with alert messages
  • Handle session invalidation gracefully
  • Test with real NFC tags during development
  • Consider using external NFC readers for advanced use cases

Limitations

  • iOS does not support writing to NFC tags (read-only)
  • Background NFC reading requires Core NFC background mode
  • Only one NFC session can be active at a time
  • Some tag types require specific entitlements

Quiz

1. What framework provides NFC reading capabilities on iOS?

Question 1 options

2. What must be added to Info.plist for NFC access?

Question 2 options

3. What does NDEF stand for?

Question 3 options

4. Can iOS apps write to NFC tags?

Question 4 options

Flashcards

Question

What is CoreNFC?

Answer

Apple's framework for reading NFC tags on iOS devices, supporting NDEF, ISO 7816, ISO 15693, FeliCa, and MIFARE.

Question

What does NDEF contain?

Answer

NFC Data Exchange Format records with typed payloads like text, URI, and smart poster data.

Question

How do you start an NFC scanning session?

Answer

Create NFCNDEFReaderSession or NFCTagReaderSession, set delegate, and call begin().

Question

What is a key limitation of iOS NFC?

Answer

iOS NFC is read-only; apps cannot write data to NFC tags.

Revision Notes

Key Takeaways

  • 1. CoreNFC provides NFC tag reading on iOS
  • 2. NFCReaderUsageDescription is required in Info.plist
  • 3. NDEF is the most common NFC tag format
  • 4. iOS NFC is currently read-only
  • 5. Always check readingAvailable before scanning

Interview Tips

  • Explain the difference between NDEF and other tag types
  • Discuss NFC use cases in mobile applications
  • Describe how to parse NDEF text and URI records

Cheat Sheet

Core NFC Quick Reference

  • NFCNDEFReaderSession - Read NDEF tags
  • NFCTagReaderSession - Read specific tag types
  • NFCNDEFMessage - Container for NDEF records
  • NFCNDEFPayload - Individual record with data
  • wellKnownTypeURIPayload() - Parse URI records
  • wellKnownTypeTextPayload() - Parse text records
  • readingAvailable - Check device support
  • alertMessage - User-facing scan instruction