Community코딩 & 개발github.com

dpearson2699/core-nfc

CoreNFC를 사용하여 NFC 태그를 읽고 씁니다. NDEF 태그 스캔, ISO7816/ISO15693/FeliCa/MIFARE 태그 읽기, NDEF 메시지 쓰기, NFC 세션 수명 주기 처리, NFC 자격 구성, iOS 앱에서 백그라운드 태그 읽기 구현 시 사용하세요.

core-nfc란 무엇인가요?

이 스킬은 iOS 앱에서 CoreNCF 프레임워크를 활용하여 NFC(근거리 무선 통신) 태그를 읽고 쓰는 기능을 제공합니다. NDEF(NFC Data Exchange Format) 태그 스캔 및 ISO7816, ISO15693, FeliCa, MIFARE 등 다양한 NFC 태그 유형을 지원하며, 개발자가 NFC 세션의 수명 주기를 관리하고 NDEF 메시지를 기록할 수 있도록 돕습니다. 또한 iOS에서 요구하는 NFC 자격(entitlements) 구성과 백그라운드 태그 읽기 기능 구현을 지원하여, 실제 기기에서의 완벽한 NFC 상호 작용을 가능하게 합니다. Xcode 프로젝트 설정, Info.plist 구성, CoreNFC 프레임워크 임포트부터 시작하여 NFCReaderSession 및 NFCTagReaderSession을 생성하고 delegate를 통해 태그 데이터를 처리하는 방법을 상세히 안내합니다. 이 스킬은 Swift 개발자를 대상으로 하며, 앱이 백그라운드에서도 NFC 태그를 감지할 수 있도록 하는 등 실제 배포 가능한 iOS 앱 개발에 필수적인 모든 단계를 다룹니다.

지원 대상~Claude Code~Codex CLI~Cursor
Part ofMobile
npx skills add https://github.com/dpearson2699/swift-ios-skills/tree/main/skills/core-nfc

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

core-nfc은(는) 무엇을 하나요?

CoreNFC를 사용하여 NFC 태그를 읽고 씁니다. NDEF 태그 스캔, ISO7816/ISO15693/FeliCa/MIFARE 태그 읽기, NDEF 메시지 쓰기, NFC 세션 수명 주기 처리, NFC 자격 구성, iOS 앱에서 백그라운드 태그 읽기 구현 시 사용하세요.

요구 사항

  • Xcode 12 이상
  • iOS 13 이상 (일부 기능은 iOS 14+ 필요)
  • 실제 iOS 기기 (시뮬레이터에서는 NFC를 지원하지 않음)
  • Apple Developer Program 멤버십 (자격 구성 필요)

설정

1. NFC 자격 추가

Xcode 프로젝트에서 다음 단계를 따르세요:

  1. Signing & Capabilities 탭으로 이동
  2. + Capability 버튼 클릭
  3. Near Field Communication Tag Reading 검색 및 추가

2. Info.plist 설정

다음 키를 Info.plist에 추가하세요:

<key>NFCReaderUsageDescription</key>
<string>이 앱은 NFC 태그를 읽고 쓰기 위해 NFC 사용 권한이 필요합니다.</string>

백그라운드 태그 읽기의 경우 추가로 다음을 포함하세요:

<key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
<array>
    <string>D2760000850101</string>
</array>

3. CoreNFC 임포트

import CoreNFC

기본 사용법

NDEF 태그 읽기

class NFCReader: NSObject, NFCNDEFReaderSessionDelegate {
    var session: NFCNDEFReaderSession?

    func startReading() {
        session = NFCNDEFReaderSession(delegate: self, queue: DispatchQueue.main, invalidateAfterFirstRead: false)
        session?.alertMessage = "NFC 태그 주변에 iPhone을 가져가세요."
        session?.begin()
    }

    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        for message in messages {
            for record in message.records {
                let payload = String(data: record.payload, encoding: .utf8) ?? "디코딩 실패"
                print("감지된 페이로드: \(payload)")
            }
        }
    }

    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        print("세션 오류: \(error.localizedDescription)")
    }
}

NDEF 태그 쓰기

func writeNDEFMessage() {
    guard let session = NFCNDEFReaderSession(delegate: self, queue: DispatchQueue.main, invalidateAfterFirstRead: true) else { return }
    session.alertMessage = "NFC 태그에 쓸 준비가 되었습니다."
    session.begin()
}

func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCNDEFTag]) {
    if tags.count > 1 {
        session.invalidate(errorMessage: "둘 이상의 태그가 감지되었습니다.")
        return
    }
    let tag = tags.first!
    session.connect(to: tag) { error in
        if error != nil {
            session.invalidate(errorMessage: "태그 연결 실패.")
            return
        }
        let payload = NFCNDEFPayload(
            format: .nfcWellKnown,
            type: "T".data(using: .utf8)!,
            identifier: Data(),
            payload: "Hello, NFC!".data(using: .utf8)!
        )
        let message = NFCNDEFMessage(records: [payload])
        tag.writeNDEF(message) { error in
            if error != nil {
                session.invalidate(errorMessage: "쓰기 실패.")
            } else {
                session.alertMessage = "성공적으로 기록되었습니다!"
                session.invalidate()
            }
        }
    }
}

ISO7816 태그 읽기

class NFCTagReader: NSObject, NFCTagReaderSessionDelegate {
    var session: NFCTagReaderSession?

    func startTagReading() {
        session = NFCTagReaderSession(pollingOption: .iso14443, delegate: self, queue: DispatchQueue.main)
        session?.alertMessage = "NFC 태그 주변에 iPhone을 가져가세요."
        session?.begin()
    }

    func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
        if case let .iso7816(isoTag) = tags.first! {
            session.connect(to: tags.first!) { error in
                if error != nil { return }
                let apdu = NFCISO7816APDU(
                    instructionClass: 0x00,
                    instructionCode: 0xA4,
                    p1Parameter: 0x04,
                    p2Parameter: 0x00,
                    data: Data([0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01]),
                    expectedResponseLength: -1
                )
                isoTag.sendCommand(apdu: apdu) { response, sw1, sw2, error in
                    print("응답: \(response as NSData), SW1: \(sw1), SW2: \(sw2)")
                }
            }
        }
    }

    func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) {
        print("세션 무효화: \(error.localizedDescription)")
    }
}

백그라운드 태그 읽기

iOS 14 이상에서 지원됩니다:

  1. Xcode에서 Signing & Capabilities에 NFC 태그 읽기 자격을 추가하세요.
  2. 읽고자 하는 ISO7816 애플리케이션 식별자(AID)로 com.apple.developer.nfc.readersession.iso7816.select-identifiers를 구성하세요.
  3. 앱이 백그라운드에 있을 때, 시스템이 일치하는 NFC 태그를 감지하고 앱을 깨웁니다.
  4. 앱 델리게이트에서 NFCNDEFReaderSession을 시작하여 태그 데이터를 검색하세요.

세션 수명 주기

  • 시작: begin()을 호출하여 NFC 스캐닝을 활성화합니다.
  • 감지: didDetect delegate 메서드가 태그와 함께 호출됩니다.
  • 연결: connect(to:completionHandler:)를 사용하여 태그와 세션을 연결합니다.
  • 통신: 적절한 태그 클래스 메서드(readNDEF, writeNDEF, sendCommand 등)를 사용합니다.
  • 무효화: 완료 후 invalidate()를 호출하거나, 오류 시 invalidate(errorMessage:)를 호출합니다.

팁과 모범 사례

  • 각 NFC 스캔에 대해 명확하고 간결한 알림 메시지를 제공하세요.
  • 항상 didInvalidateWithError delegate 메서드를 구현하여 오류를 우아하게 처리하세요.
  • 여러 태그가 동시에 감지되는 상황을 방지하기 위해 태그 수를 확인하세요.
  • 민감한 데이터가 포함된 NDEF 페이로드는 적절히 처리하세요.
  • 실제 기기에서 테스트하세요 — 시뮬레이터는 NFC를 지원하지 않습니다.
  • Apple의 CoreNFC 문서에서 추가 세부 정보를 확인하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

dpearson2699/accessorysetupkit

Discover and configure Bluetooth and Wi-Fi accessories using AccessorySetupKit. Use when presenting a privacy-preserving accessory picker, defining discovery descriptors for BLE or Wi-Fi devices, handling accessory session events, migrating from CoreBluetooth permission-based scanning, or setting up accessories without requiring broad Bluetooth permissions.

dpearson2699/activitykit

Implement, review, or improve Live Activities and Dynamic Island experiences in iOS apps using ActivityKit. Use when building real-time updating widgets for the Lock Screen and Dynamic Island — delivery tracking, sports scores, ride-sharing status, workout timers, media playback, or any time-sensitive information that updates in real time. Also use when working with ActivityKit, ActivityAttributes, Activity lifecycle (request/update/end), Dynamic Island layouts (compact/minimal/expanded), push-to-update Live Activities, or Lock Screen live widgets.

dpearson2699/adattributionkit

Measure ad effectiveness with privacy-preserving attribution using AdAttributionKit. Use when registering ad impressions, handling attribution postbacks, updating conversion values, implementing re-engagement attribution, configuring publisher or advertiser apps, or replacing SKAdNetwork with AdAttributionKit for ad measurement.

dpearson2699/alarmkit

Implement AlarmKit alarms and countdown timers for iOS and iPadOS with Lock Screen, Dynamic Island, and Apple Watch system UI. Covers AlarmManager scheduling, AlarmAttributes and AlarmPresentation, AlarmButton stop and snooze actions, authorization, state observation, and Live Activity integration. Use when building wake-up alarms, countdown timers, or alarm-style alerts that need Apple's system alarm experience.

dpearson2699/app-clips

Build iOS App Clips with invocation URLs, App Clip Codes, NFC, QR codes, Safari banners, Maps, Messages, target setup, App Store Connect experiences, size/capability constraints, NSUserActivity routing, SKOverlay promotion, App Group/keychain handoff, ephemeral notifications, location confirmation, and full-app migration. Use when creating App Clips or wiring App Clip invocation, experience configuration, or full-app handoff.

dpearson2699/app-intents

Implement App Intents for Siri, Shortcuts, Spotlight, widgets, Control Center, and Apple Intelligence on iOS. Covers AppIntent actions, AppEntity and EntityQuery models, AppShortcutsProvider phrases, IndexedEntity Spotlight indexing, WidgetConfigurationIntent, SnippetIntent, and assistant schemas. Use when exposing app actions or entities to system surfaces.

dpearson2699/apple-on-device-ai

Integrate on-device AI using Foundation Models framework, Core ML, and open-source LLM runtimes on Apple Silicon. Covers Foundation Models (LanguageModelSession, @Generable, @Guide, SystemLanguageModel, structured output, tool calling), Core ML (coremltools, model conversion, quantization, palettization, pruning, Neural Engine, MLTensor), MLX Swift (transformer inference, unified memory), and llama.cpp (GGUF, cross-platform LLM). Use when building tool-calling AI features, working with guided generation schemas, converting models, or running on-device inference.

dpearson2699/appmigrationkit

Transfer app data to or from other platforms using AppMigrationKit. Use when implementing system-orchestrated one-time migration between iOS and Android or another platform, building an AppMigrationExtension, packaging transportable resources with ResourcesArchiver, importing resources on the destination device, reporting import progress, handling migration errors and app group cleanup, checking MigrationStatus, or testing migration code with AppMigrationTester.

dpearson2699/app-store-review

Prepare for App Store review and prevent rejections. Covers App Store review guidelines, app rejection reasons, PrivacyInfo.xcprivacy privacy manifest requirements, required API reason codes, in-app purchase IAP and StoreKit rules, App Store Guidelines compliance, ATT App Tracking Transparency, EU DMA Digital Markets Act, HIG compliance checklist, app submission preparation, review preparation, metadata requirements, entitlements, widgets, and Live Activities review rules. Use when preparing for App Store submission, fixing rejection reasons, auditing privacy manifests, implementing ATT consent flow, configuring StoreKit IAP, or checking HIG compliance.

dpearson2699/audioaccessorykit

Support audio accessory features like automatic switching using AudioAccessoryKit. Use when implementing automatic audio routing for paired accessories, registering audio accessory configuration from the container app, updating placement or connected audio source identifiers from an app extension, or handling AccessoryControlDevice capabilities and errors.

dpearson2699/authentication

Implement iOS authentication flows with AuthenticationServices and LocalAuthentication. Use when building Sign in with Apple, passkey/WebAuthn registration or sign-in with ASAuthorizationPlatformPublicKeyCredentialProvider, ASAuthorizationController credential state and revocation handling, ASWebAuthenticationSession OAuth or third-party login, Password AutoFill, identity-token server validation, or local biometric re-authentication with LAContext.

dpearson2699/avkit

Create media playback experiences using AVKit. Use when adding video players with AVPlayerViewController, enabling Picture-in-Picture, routing media with AirPlay, using SwiftUI VideoPlayer views, configuring transport controls, displaying subtitles and closed captions, or integrating AVFoundation playback with system UI.

dpearson2699/background-processing

Schedule and execute background work on iOS using BGTaskScheduler. Use when registering BGAppRefreshTask for short background fetches, BGProcessingTask for long-running maintenance, BGContinuedProcessingTask (iOS 26+) for foreground-started work that continues in background, background URLSession downloads, or background push notifications. Covers Info.plist configuration, expiration handling, task completion, and debugging with simulated launches.

dpearson2699/browserenginekit

Build alternative browser engines using BrowserEngineKit. Use when developing a non-WebKit browser engine for iOS/iPadOS in supported regions, managing web content/rendering/networking extension processes, configuring GPU and networking process capabilities, checking alternative-engine device eligibility, or reviewing BrowserEngineKit entitlements and Info.plist setup.

dpearson2699/callkit

Implement VoIP calling with CallKit and PushKit. Use when building incoming/outgoing call flows, registering for VoIP push notifications, configuring CXProvider and CXCallController, handling call actions, coordinating audio sessions, or creating Call Directory extensions for caller ID and call blocking.

dpearson2699/carplay

Build CarPlay-enabled apps using the CarPlay framework. Use when creating navigation, audio, communication, EV charging, parking, or food ordering apps for the car display, working with CPTemplateApplicationScene, CPInterfaceController template hierarchies, CPListTemplate, CPMapTemplate, CPNowPlayingTemplate, configuring CarPlay entitlements, or integrating with CarPlay Simulator for testing.

dpearson2699/cloudkit

Implement, review, or improve CloudKit and iCloud sync in iOS/macOS apps. Use when working with CKContainer, CKRecord, CKQuery, CKSubscription, CKSyncEngine, CKShare, NSUbiquitousKeyValueStore, or iCloud Drive file coordination; when syncing SwiftData models via ModelConfiguration with cloudKitDatabase; when handling CKError codes for conflict resolution, network failures, or quota limits; or when checking iCloud account status before performing sync operations.

dpearson2699/contacts-framework

Read, create, update, and pick contacts using the Contacts and ContactsUI frameworks. Use when fetching contact data, saving new contacts, wrapping CNContactPickerViewController in SwiftUI, handling contact permissions, or working with CNContactStore fetch and save requests.

dpearson2699/core-bluetooth

Build direct Bluetooth Low Energy workflows with Core Bluetooth. Use when implementing BLE central or peripheral GATT communication, scanning or connecting with CBCentralManager, discovering services and characteristics, reading/writing/subscribing with CBPeripheral, publishing local services with CBPeripheralManager, handling Bluetooth authorization, background BLE modes, state restoration, write flow control, or CBUUID-based workflows. For privacy-preserving accessory setup/picker flows, use accessorysetupkit first and return here for post-setup GATT communication.

dpearson2699/coreml

Integrate Core ML models in iOS apps for on-device machine learning inference. Covers model loading (.mlmodel, .mlpackage, .mlmodelc), predictions with auto-generated classes and MLFeatureProvider, compute unit configuration (CPU, GPU, Neural Engine), MLTensor, VNCoreMLRequest, MLComputePlan, multi-model pipelines, and deployment strategies. Use when loading Core ML models, making predictions, configuring compute units, or profiling model performance.

관련 스킬