• Stars
    star
    506
  • Rank 87,236 (Top 2 %)
  • Language
    Swift
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ“± Example showing how to use the Core NFC API in iOS

πŸ“± iOS 11 NFC-Example

A quick example showing how to use the Core NFC API in iOS 11 and Swift 4.

Prerequisites

  • Xcode 9
  • iOS 11 device (iPhone 7 / iPhone 7 Plus)
  • NFC-permissions added to your Info.plist:
<key>NFCReaderUsageDescription</key>
<string>YOUR_PRIVACY_DESCRIPTION</string>
  • Xcode capability "Near Field Communication Tag Reading" enabled OR
  • NFC capability-key added to your project's .entitlements file:
<key>com.apple.developer.nfc.readersession.formats</key>
<array>
  <string>NDEF</string>
</array>
  • Provisioning Profile entitled with the NFC Tag Reading capability:

iOS Developer Center: NFC Capability

Understanding NDEF-Records

In order to work with NFC-tags, it is fundamental to understand the NDEF (NFC Data Exchange Format) specification. Whenever CoreNFC discovers a new tag, the didDetectNDEFs delegate method will provide an array of NDEF messages ([NFCNDEFMessage]). Usually, there is only one NDEF message included, but the specification keeps it flexible to provide multiple messages at the same time.

Every NFCNDEFMessage includes an array of payload-records ([NFCNDEFPayload]) that hold the actual information the developer is interested in. There are currently four (undocumented) properties in the CoreNFC framework to access those:

  1. typeNameFormat: The type name format (TNF) describes the data-structure of the related record. There are seven types that can be used via the enumeration NFCTypeNameFormat:
    1. .empty: There record is empty and does not contain any information
    2. .nfcWellKnown: The payload is known and defined by the Record Type Definition (RTD), for example RTD Text / URI.
    3. .media: The payload includes a final / intermediate chunk of data defined by the mime-type (RFC2046)
    4. .absoluteURI: The record contains an absolute URI resource (RFC3986)
    5. .nfcExternal: The record contains a value that uses an external RTD name specifiction
    6. .unknown: The record type is unknown, the type length has to be set to 0.
    7. .unchanged: The record payload is the intermediate or even final chunk of data. This can be used when there is a large number of data that is splitted into multiple chunks of data.
  2. type: The Record Type Definition (RTD) of the record. iOS 11 describes it as a Data type, Android has constants (like RTD_TEXT), so either later iOS 11 beta versions will expose similar ones as well, or the developer needs to create enumerations for it. I will try keep this updated during the Beta cycles! Update: Not available in iOS 11.
  3. identifier: A unique identifier of the record.
  4. payload: The actual payload of the record. Accessing it depends on the specified typeNameFormat as described above.

Getting Started

First, import the CoreNFC framework.

import CoreNFC

Next, create 2 properties: Your session and an array of discovered tag-messages:

// Reference the NFC session
private var nfcSession: NFCNDEFReaderSession!
    
// Reference the found NFC messages
private var nfcMessages: [[NFCNDEFMessage]] = []

After that, assign and start your nfcSession:

// Create the NFC Reader Session when the app starts
self.nfcSession = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)

// A custom description that helps users understand how they can use NFC reader mode in your app.
self.nfcSession.alertMessage = "You can hold you NFC-tag to the back-top of your iPhone"

// Begin scanning
self.nfcSession.begin()

Finally, listen for NFC-related events by writing an extension that implements the NFCNDEFReaderSessionDelegate:

extension NFCTableViewController : NFCNDEFReaderSessionDelegate {
    
    // Called when the reader-session expired, you invalidated the dialog or accessed an invalidated session
    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        print("Error reading NFC: \(error.localizedDescription)")
    }
    
    // Called when a new set of NDEF messages is found
    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        print("New NFC Tag detected:")
        
        for message in messages {
            for record in message.records {
                print("Type name format: \(record.typeNameFormat)")
                print("Payload: \(record.payload)")
                print("Type: \(record.type)")
                print("Identifier: \(record.identifier)")
            }
        }
        
        // Add the new messages to our found messages
        self.nfcMessages.append(messages)
        
        // Reload our table-view on the main-thread to display the new data-set
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
}

Optionally, since we use a UITableView to display the discovered messages, prepare your table-view delegates:

extension NFCTableViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.nfcMessages.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.nfcMessages[section].count
    }
    
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let numberOfMessages = self.nfcMessages[section].count
        let headerTitle = numberOfMessages == 1 ? "One Message" : "\(numberOfMessages) Messages"
        
        return headerTitle
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NFCTableCell", for: indexPath) as! NFCTableViewCell
        let nfcTag = self.nfcMessages[indexPath.section][indexPath.row]
        
        cell.textLabel?.text = "\(nfcTag.records.count) Records"
        
        return cell
    }
}

That's it! Run the app on your device and scan your NFC NDEF-Tag.

Example Output

New NFC Messages (1) detected:
 - 2 Records:
   - TNF (TypeNameFormat): NFC Well Known
   - Payload: google.com
   - Type: 1 bytes
   - Identifier: 0 bytes

   - TNF (TypeNameFormat): NFC Well Known
   - Payload: enTest
   - Type: 1 bytes
   - Identifier: 0 bytes

User Experiences

Initial tests of another user (thanks @tinue) shown these following results:

  1. Scanning an NDEF-tag usually works once directly after rebooting the iPhone. From then on, it may or may not work, usually it doesn't work and another reboot is required. This was seen with 1-4 of iOS 11.
  2. If the RFID-tag is fresh (empty), or does not contain an NDEF-tag (e.g. a credit-card), the reader times out (error 201).
  3. If the RFID-tag contains encrypted sectors, the reader throws error 200 (readerSessionInvalidationErrorUserCanceled).

RFID Functionality

In this example, we used the NFCNDEFReaderSession to handle NDEF NFC-chips. There actually is another class inside CoreNFC, called NFCISO15693ReaderSession. ISO15693 is the specification for RFID-tags, and it comes along with own delegates and a class describing an RFID-tag (NFCISO15693Tag).

I have played around with that API as well and added the RFID button to the current implementation, so you can switch between NFC- and RFID-detection. You can even send custom commands to the RFID-chip as demonstrated in the readerSession:didDetectTags: delegate and the NFCISO15693CustomCommandConfiguration class.

Unfortunately, iOS 11 Beta 1-2 will throw a Feature not supported error and Beta 3-4 will open the scan-dialog but abort immediately with an error. They probably did not finish implementing it, so raise a radar to remind them πŸ™Œ! It will likely result in another value inside the com.apple.developer.nfc.readersession.formats entitlements key as well. Using something like ISO15693 or RFID will not work so far and prevent the build from finishing. Let's see what Apple will publish in the upcoming Beta versions of iOS 11! πŸ™‚

UPDATE: Still no clarification from Apple in the final version of iOS 11. Feel free to follow this discussion if you have related issues.

References

I used the following resources to get started with NDEF NFC-tags:

Cross-Platform Usage

If you are using a cross-platform solution for your application, Appcelerator Titanium has an open source NFC module for both Android and iOS.

Author

Hans KnΓΆchel (@hansemannnn)

More Repositories

1

titanium-googlemaps

πŸ—Ί Use the Google Maps SDK in Titanium
Objective-C
87
star
2

iOS11-QR-Code-Example

Example showing how to use the QR-code detection API (VNDetectBarcodesRequest) in iOS 11.
Swift
85
star
3

titanium-firebase

Use the Firebase SDK in Axway Titanium πŸš€
JavaScript
60
star
4

chrome-mojave-checkbox-extension

A tiny Google Chrome extension to fix the zoom-level on macOS 11.14 (Mojave) Beta.
JavaScript
56
star
5

facebook-live-ios

πŸ“Ί A Swift utility "FBSDKLiveVideo" to stream Facebook Live videos on iOS
Swift
55
star
6

iOS12-CarPlay-Example

An example of using the CarPlay framework in iOS 12 and later.
Swift
48
star
7

titanium-bluetooth

πŸ“‘ Native iOS / Android Bluetooth support for the Axway Titanium SDK
Objective-C
46
star
8

titanium-firebase-cloud-messaging

Use the Firebase Cloud Messaging SDK in Axway Titanium πŸš€ Edit
Objective-C
45
star
9

titanium-review-dialog

Use the native iOS 10.3+ SKStoreReviewController and Android dialog in Appcelerator Titanium.
C++
43
star
10

iOS12-Siri-Shortcuts-Example

An example of using Siri Shortcuts in iOS 12 and later.
Swift
42
star
11

titanium-image-crop

An easy to use iOS image cropping tool based on TOCropViewController.
Objective-C
38
star
12

titanium-firebase-analytics

Use the Firebase Analytics SDK in Axway Titanium πŸš€
Objective-C
34
star
13

titanium-firebase-core

Use the Firebase Core SDK in the Titanium SDK πŸš€
Objective-C
31
star
14

titanium-google-signin

Use the native Google Sign In SDK in Appcelerator Titanium.
Objective-C
30
star
15

titanium-arkit

Use the iOS 11 ARKit API in Axway Titanium
Objective-C
28
star
16

titanium-dark-mode

Full support for iOS 13+ / Android 10+ dark mode (semantic colors and images) in Appcelerator Titanium
JavaScript
26
star
17

studentenfutter-app

🍱 Mobile App to show canteen meals in Germany.
JavaScript
23
star
18

titanium-vision

Use the Vision & VisionKit framework with Appcelerator Titanium.
Objective-C
22
star
19

ti.lottie

πŸ–Ό Support for the @airbnb Lottie library in Titanium
Objective-C
21
star
20

ti.onepassword

πŸ” Support the 1Password App Extension with Titanium Mobile
Objective-C
20
star
21

ti.splashview

πŸ’¦ Support for the splash-screen library CBZSplashView in Appcelerator Titanium.
Objective-C
19
star
22

ti.accountkit

DEPRECATED -- πŸ” Use the Facebook AccountKit iOS-SDK with Titanium Mobile.
Objective-C
18
star
23

CloudSharingControllerExample

An example on how to use the new iOS10 API "UICloudSharingController" in Swift
Swift
18
star
24

titanium-crashlytics

Use the native Crashlytics SDK in Titanium (iOS / Android).
Objective-C
17
star
25

titanium-coreml

Use the CoreML framework in iOS 11+ with Appcelerator Titanium
Objective-C
16
star
26

ti.keyframes

πŸ–Ό Support for the @facebook Keyframes library in Titanium
Objective-C
16
star
27

abifestival-app

Cross-platform festival-app built with the Appcelerator Titanium framework
JavaScript
16
star
28

titanium-scanner

Use the iOS 13+ "VisionKit" document scanner API in Appcelerator Titanium.
Swift
16
star
29

titanium-image-filters

Use the GPUImage library to apply pre-built and custom filters to images in Titanium
Objective-C
16
star
30

titanium-qrcode

A simple library for generating and scanning QR codes natively. Built with Swift (iOS) and Kotlin (Android) πŸš€
Objective-C
16
star
31

titanium-imagepicker

Swift
15
star
32

titanium-calendar

An easy to use iOS modal calendar for selecting dates. Based on the awesome PDTSimpleCalendar library.
Objective-C
15
star
33

titanium-apple-pay

πŸ’° Support for iOS Apple Pay in Titanium
Objective-C
14
star
34

titanium-android-bottom-sheet-dialog

Use the native Android BottomSheet view in Appcelerator Titanium.
Java
14
star
35

hyperloop-robot

πŸ€– Use Appcelerator Hyperloop to program for the Sphero iOS-SDK.
JavaScript
14
star
36

titanium-material

Use the native Material UI/UX framework (https://github.com/CosmicMind/Material) in Titanium!
Objective-C
14
star
37

titanium-context-menu

Use the `UIPreviewInteraction` and `UIMenu` API in the Titanium SDK.
Objective-C
13
star
38

titanium-iap

Support for native cross-platform in-app-purchasing API's in Titanium. This repository represents a modern alternative to ti.storekit (iOS) and ti.inappbilling (Android).
Objective-C
13
star
39

titanium-document-picker

Java
12
star
40

titanium-ios-document-picker

Use the native UIDocumentMenuViewController in Titanium and Hyperloop.
JavaScript
12
star
41

ti.fluidview

🌊 Support for the BAFluidView with Titanium Mobile
Objective-C
12
star
42

titanium-replaykit

Use the iOS ReplayKit API's to record the app screen in Titanium and Hyperloop.
12
star
43

titanium-drag-and-drop

Native cross platform "Drag and Drop" functionality in Axway Titanium.
Objective-C
12
star
44

iOS16-Passkeys-Sample

This project explores the capabilities of the new iOS 16+ Passkeys API to support password-less authentications.
Swift
11
star
45

titanium-es6-sample

An ES6+ sample app for Appcelerator Titanium.
JavaScript
11
star
46

titanium-app-tracking-transparency

JavaScript
11
star
47

titanium-deep-learning

Use the JetPac DeepBeliefSDK framework in Appcelerator Titanium
Python
11
star
48

titanium-swift-module-example

Utilize Swift to build native modules for Appcelerator Titanium.
Objective-C
11
star
49

titanium-notification-service-extension

An example implementation of using a native iOS Notification Service Extension (to display images in remote push notification) in Titanium.
Swift
11
star
50

titanium-parse-live-query

Use the Parse & Parse Live Query SDK's in Axway Titanium.
Objective-C
10
star
51

ti.lineapro

πŸ“Έ Use the LineaPro iOS-SDK with Appcelerator Titanium
Objective-C
10
star
52

titanium-ios-business-chat

Use the iOS 11.3+ BusinessChat framework in Appcelerator Titanium and Hyperloop
JavaScript
10
star
53

titanium-carplay

Use the iOS 12+ CarPlay framework in Appcelerator Titanium.
Objective-C
10
star
54

titanium-sirikit

Support for the native iOS SiriKit API in Appcelerator Titanium
JavaScript
9
star
55

ti.spotify

🎢 Support for the Spotify iOS SDK in the Titanium Mobile SDK.
Objective-C
9
star
56

titanium-rounded-tab-group

A lightweight module to apply a native rounded tab groups (no custom view) in Appcelerator Titanium.
Objective-C
9
star
57

ti.glpaint

Support for OpenGL drawing in Titanium.
Objective-C
9
star
58

ti.siriview

Support for the iOS library SCSiriWaveformView in Titanium Mobile
Objective-C
9
star
59

titanium-pencilkit

Use the native iOS 13+ PencilKit framework in Titanium.
Objective-C
8
star
60

titanium-firebase-performance

Use the Firebase Performance SDK in Axway Titanium πŸš€
Objective-C
8
star
61

iOS12-Natural-Language-Example

An example of using Natural Language framework in iOS 12 and later.
Swift
8
star
62

titanium-homekit

Support for the HomeKit framework in Appcelerator Titanium
Objective-C
8
star
63

titanium-tooltip

Use the native AMPopTip (iOS) and ViewTooltip (Android) library to display tooltips above any view and window in Titanium!
Objective-C
7
star
64

titanium-bottom-sheet

Kotlin
7
star
65

SpeechRecognitionExample

An example on how to use the new iOS10 API "SFSpeechRecognizer" in Swift
Swift
7
star
66

titanium-weather-kit

Use the iOS 16+ WeatherKit APIs in Titanium!
Swift
7
star
67

titanium-empty-state

Use the (awesome) DZNEmptyDataSet library in your Titanium iOS projects.
Objective-C
7
star
68

titanium-pdf-tools

Merges a given number of PDF files into one file using the PDFKit framework
Swift
7
star
69

titanium-widget-kit

Use native iOS / Android widgets in Titanium.
Java
7
star
70

ti.storyboard

Support for launch screen storyboards using Titanium Mobile and Appcelerator Studio.
JavaScript
7
star
71

titanium-firebase-database

Use the Firebase Realtime Database SDK in Axway Titanium πŸš€
Objective-C
7
star
72

cspec-titanium-hyperloop-modules

CSPEC for native Titanium Mobile modules using Hyperloop technologies.
7
star
73

hyperloop-google-maps

Use the GoogleMaps SDK with Axway Hyperloop in your Titanium project.
JavaScript
7
star
74

titanium-firebase-demo

A cross-platform sample app demonstrating how to use the Titanium Firebase modules in Appcelerator Titanium.
JavaScript
7
star
75

titanium-aws

☁️ Use the Amazon AWS SDK with Appcelerator Titanium
Objective-C
7
star
76

titanium-firebase-auth

Use the Firebase Autentication SDK in Axway Titanium πŸš€
Objective-C
7
star
77

Ti.Realm

πŸ—ƒ Use the Realm iOS-SDK with Titanium Mobile.
Objective-C
6
star
78

titanium-amplitude

Titanium Amplitude - Use the native Amplitude iOS/Android SDK in Titanium
Objective-C
6
star
79

titanium-loading-hud

A simple loading HUD that uses native UI elements to present a modal loading indicator.
JavaScript
6
star
80

ti.sphero

Native module to use the Sphero iOS SDK with Titanium Mobile
Objective-C
6
star
81

titanium-thumbnail-generator

Generate thumbnails for common file types (e.g. PDF) natively in Appcelerator Titanium.
Java
6
star
82

ti.barcodescanner

Refactored version of Ti.Barcode using the AVCaptureDevice API
Objective-C
6
star
83

titanium-widget-kit-sample-app

A sample app demonstrating the WidgetKit capabilitites of Titanium in native iOS development.
C
6
star
84

titanium-tesseract-ocr

Use the native TesseractOCR iOS-framework in Appcelerator Titanium.
C++
6
star
85

titanium-stripe

Use the native Stripe iOS/Android SDK in Appcelerator Titanium.
Objective-C
6
star
86

react-native-storekit

iOS In-App Purchase in React Native using the StoreKit framework. **Unmaintained** in favor of the Titanium "Ti.StoreKit" module.
Objective-C
6
star
87

ti.flic

πŸ”˜ Use the IoT Flic iOS-SDK with Titanium Mobile
Objective-C
5
star
88

titanium-intercom

Use the native iOS / Android Intercom SDK's in Appcelerator Titanium.
Objective-C
5
star
89

titanium-appodeal

Supporting the native Appodeal SDK (iOS/Android) in Titanium.
Java
5
star
90

titanium-reminders

Access the native iOS / macOS reminders (get, update, delete) in TiDev / Titanium.
Swift
5
star
91

titanium-giphy

Use the native Giphy iOS- and Android SDK's to select GIFs and display them in your app.
Objective-C
5
star
92

ti.colorpicker

Support for choosing different colors from a picker view.
Objective-C
5
star
93

iOS11-PasswordFill-Example

Example showing how to use the PasswordFill API in iOS 11.
Swift
5
star
94

titanium-sample-hyperloop-es6

Use ES6+ in Appcelerator Hyperloop 🀘
JavaScript
5
star
95

titanium-firebase-storage

Use the Firebase Storage SDK in Axway Titanium πŸš€
Objective-C
5
star
96

applepaydemo

Example app showing how to use the Ti.ApplePay module.
JavaScript
5
star
97

titanium-android-tabbed-bar

Use the native MaterialButtonToggleGroup API for tabbed-bars
Java
5
star
98

titanium-slack-text-view-controller

Use the awesome (!) Slack TextViewController in Titanium!
Objective-C
5
star
99

hyperloop-socketio

Use the Socket.io iOS-SDK in Titanium with Hyperloop
JavaScript
4
star
100

titanium-firebase-crash-reporting

DEPRECATED: USE TITANIUM-CRASHLYTICS INSTEAD
Shell
4
star