All Projects → hansemannn → Ios Nfc Example

hansemannn / Ios Nfc Example

📱 Example showing how to use the Core NFC API in iOS

Programming Languages

swift
15916 projects
swift4
162 projects

Projects that are alternatives of or similar to Ios Nfc Example

NFCSupport
Support library for NFC NDEF Records
Stars: ✭ 20 (-95.83%)
Mutual labels:  nfc, ios11
Ios11 Pdfkit Example
Sample code for PDFKit on iOS 11.
Stars: ✭ 105 (-78.12%)
Mutual labels:  example, ios11
Learning Rust
Rust 学习之路 > Rust Programming Tutorial, include articles, interview, example, problems.
Stars: ✭ 376 (-21.67%)
Mutual labels:  example
Electron With Express
A simple app that demonstrates spawning an Express app from Electron
Stars: ✭ 454 (-5.42%)
Mutual labels:  example
Ios 11.1.2 15b202 Jailbreak
iOS 11.1.2 (15B202) Jailbreak
Stars: ✭ 413 (-13.96%)
Mutual labels:  ios11
Jetpack Compose Whatsapp Clone
An example project to demonstrate how to build WhatsApp using Jetpack Compose.
Stars: ✭ 386 (-19.58%)
Mutual labels:  example
Cards
Awesome iOS 11 appstore cards in swift 5.
Stars: ✭ 4,017 (+736.88%)
Mutual labels:  ios11
Ahdownloadbutton
Customizable download button with progress and transition animations. It is based on Apple's App Store download button.
Stars: ✭ 370 (-22.92%)
Mutual labels:  ios11
Espressif
all espressif stuff will committed here
Stars: ✭ 477 (-0.62%)
Mutual labels:  example
Vsmartcard
umbrella project for emulation of smart card readers or smart cards
Stars: ✭ 404 (-15.83%)
Mutual labels:  nfc
Dva Example User Dashboard
👲 👬 👨‍👩‍👧 👨‍👩‍👦‍👦
Stars: ✭ 446 (-7.08%)
Mutual labels:  example
Mifareonetool
A GUI Mifare Classic tool on Windows(停工/最新版v1.7.0)
Stars: ✭ 404 (-15.83%)
Mutual labels:  nfc
Firebase Instagram
📸 Instagram clone with Firebase Cloud Firestore, Expo, and React Native 😁😍
Stars: ✭ 389 (-18.96%)
Mutual labels:  example
Nfcgate
An NFC research toolkit application for Android
Stars: ✭ 425 (-11.46%)
Mutual labels:  nfc
Go Todo Rest Api Example
📚 A RESTful API example for simple todo application with Go
Stars: ✭ 385 (-19.79%)
Mutual labels:  example
Nfcpassportreader
NFCPassportReader for iOS 13
Stars: ✭ 458 (-4.58%)
Mutual labels:  nfc
Awesome Flutter Ui
10+ flutter(android, ios) UI design examples ⚡️ - login, books, profile, food order, movie streaming, walkthrough, widgets
Stars: ✭ 372 (-22.5%)
Mutual labels:  example
Easynavigation
一款超级简单的导航条管理工具。完全自定义导航条。没有UINavigationBar 和 UINavigationItem 这两个类。完全是对UIView的操作。
Stars: ✭ 393 (-18.12%)
Mutual labels:  ios11
React Redux Complete Example
A react+redux example project based on the folder structure proposed here: https://github.com/alexnm/re-ducks
Stars: ✭ 415 (-13.54%)
Mutual labels:  example
Facecropper
✂️ Crop faces, inside of your image, with iOS 11 Vision api.
Stars: ✭ 479 (-0.21%)
Mutual labels:  ios11

📱 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)

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].