NFCReaderWriter which supports to read data from NFC chips(iOS 11), write data to NFC chips(iOS 13) and read NFC tags infos(iOS 13) by iOS devices.

Overview

NFCReaderWriter

Version Carthage Compatible License Platform Swift

Description

NFCReaderWriter which supports to read data from NFC chips(iOS 11), write data to NFC chips(iOS 13) and read NFC tags infos(iOS 13) by iOS devices. Compatible with both Swift and Objective-C.

Installation

CocoaPods

pod 'NFCReaderWriter'

Carthage

github "janlionly/NFCReaderWriter"

Swift Package Manager

.package(url: "https://github.com/janlionly/NFCReaderWriter.git", .upToNextMajor(from: "1.1.4")),

Usage

  1. Set your provisioning profile to support for Near Field Communication Tag Reading;

  2. Open your project target, on Signing & Capabilities tab, add the Capability of Near Field Communication Tag Reading;

  3. Remember to add NFCReaderUsageDescription key for descriptions to your Info.plist.

  4. Support for read tag identifier(iOS 13), you should add your NFC tag type descriptions to your Info.plist.

    (eg: like com.apple.developer.nfc.readersession.felica.systemcodes, com.apple.developer.nfc.readersession.iso7816.select-identifiers)

More information please run demo above.

/// ----------------------
/// 1. NFC Reader(iOS 11):
/// ----------------------
// every time read NFC chip's data, open a new session to detect
readerWriter.newReaderSession(with: self, invalidateAfterFirstRead: true, alertMessage: "Nearby NFC Card for read")
readerWriter.begin()

// implement NFCReaderDelegate to read NFC chip's data
func reader(_ session: NFCReader, didDetectNDEFs messages: [NFCNDEFMessage]) {
  for message in messages {
    for (i, record) in message.records.enumerated() {
      print("Record \(i+1): \(String(data: record.payload, encoding: .ascii))")
      // other record properties: typeNameFormat, type, identifier
    }
  }
  readerWriter.end()
}

/// ----------------------
/// 2. NFC Writer(iOS 13):
/// ----------------------
// every time write data to NFC chip, open a new session to write
readerWriter.newWriterSession(with: self, isLegacy: true, invalidateAfterFirstRead: true, alertMessage: "Nearby NFC Card for write")
readerWriter.begin()

// implement NFCReaderDelegate to write data to NFC chip
func reader(_ session: NFCReader, didDetect tags: [NFCNDEFTag]) {
	  // here for write test data
    var payloadData = Data([0x02])
    let urls = ["apple.com", "google.com", "facebook.com"]
    payloadData.append(urls[Int.random(in: 0..<urls.count)].data(using: .utf8)!)

    let payload = NFCNDEFPayload.init(
      format: NFCTypeNameFormat.nfcWellKnown,
      type: "U".data(using: .utf8)!,
      identifier: Data.init(count: 0),
      payload: payloadData,
      chunkSize: 0)

    let message = NFCNDEFMessage(records: [payload])

    readerWriter.write(message, to: tags.first!) { (error) in
        if let err = error {
            print("ERR:\(err)")
        } else {
            print("write success")
        }
        self.readerWriter.end()
     }
}

/// -------------------------
/// 3. NFC Tag Reader(iOS 13)
/// -------------------------
readerWriter.newWriterSession(with: self, isLegacy: false, invalidateAfterFirstRead: true, alertMessage: "Nearby NFC card for read tag identifier")
readerWriter.begin()

// implement NFCReaderDelegate to read tag info from NFC chip
func reader(_ session: NFCReader, didDetect tag: __NFCTag, didDetectNDEF message: NFCNDEFMessage) {
    let tagId = readerWriter.tagIdentifier(with: tag)
    let content = contentsForMessages([message])

    DispatchQueue.main.async {
      self.tagIdLabel.text = "Read Tag Identifier:\(tagId.hexadecimal)"
      self.tagInfoTextView.text = "TagInfo:\n\(tagInfosDetail)\nNFCNDEFMessage:\n\(content)"
    }
    self.readerWriter.end()
}

/// --------------------------------
/// other NFCReaderDelegate methods:
/// --------------------------------
func readerDidBecomeActive(_ session: NFCReader) {
  print("Reader did become")
}
func reader(_ session: NFCReader, didInvalidateWithError error: Error) {
  print("ERROR:\(error)")
}

Version Updates

V1.1.4

// You can change alertMessage anywhere before call 'readerWriter.end()' as follow:
readerWriter.alertMessage = "NFC Tag Info detected"

V1.1.3

// Updated: add alertMessage property when detected NFC successfully 
readerWriter.detectedMessage = "Your Read/Write NFC successful content."

V1.1.2

// Support for reading tag infos and NDEFMessage when the NFC chip was scanned once
func reader(_ session: NFCReader, didDetect tag: __NFCTag, didDetectNDEF message: NFCNDEFMessage)

V1.0.6

// Support for reading tag identifier
func reader(_ session: NFCReader, didDetect tag: __NFCTag) {
  let tagId = readerWriter.tagIdentifier(with: tag)
  // ...
}

Requirements

  • iOS 11.0+
  • Swift 4.2 to 5.2

Author

Visit my github: janlionly
Contact with me by email: [email protected]

Contribute

I would love you to contribute to NFCReaderWriter

License

NFCReaderWriter is available under the MIT license. See the LICENSE file for more info.

You might also like...
⛓ Easy to Read and Write Multi-chain Animations Lib in Objective-C and Swift.
⛓ Easy to Read and Write Multi-chain Animations Lib in Objective-C and Swift.

中文介绍 This project is inspired by JHChainableAnimations! Why Choose LSAnimator & CoreAnimator? You can write complex and easy-to-maintain animations in

Blocks Based Bluetooth LE Connectivity framework for iOS/watchOS/tvOS/OSX. Quickly configure centrals & peripherals, perform read/write operations, and respond characteristic updates.
Blocks Based Bluetooth LE Connectivity framework for iOS/watchOS/tvOS/OSX. Quickly configure centrals & peripherals, perform read/write operations, and respond characteristic updates.

ExtendaBLE Introduction ExtendaBLE provides a very flexible syntax for defining centrals and peripherals with ease. Following a blocks based builder a

 📝 Read, update and write your Xcode projects
📝 Read, update and write your Xcode projects

XcodeProj XcodeProj is a library written in Swift for parsing and working with Xcode projects. It's heavily inspired by CocoaPods XcodeProj and xcode.

CodableCSV - Read and write CSV files row-by-row or through Swift's Codable interface.

CodableCSV provides: Imperative CSV reader/writer. Declarative CSV encoder/decoder. Support multiple inputs/outputs: Strings, Data blobs, URLs, and St

CSVParser - A swift library for fast read and write CSV file

CSVParser A swift library for fast read and write CSV file. This library supports all Apple platform and Linux. List to do get column by string subscr

Write amazing, strong-typed and easy-to-read NSPredicate.

PredicateFlow Write amazing, strong-typed and easy-to-read NSPredicate. This library allows you to write flowable NSPredicate, without guessing attrib

Write amazing, strong-typed and easy-to-read NSPredicate.

PredicateFlow Write amazing, strong-typed and easy-to-read NSPredicate. This library allows you to write flowable NSPredicate, without guessing attrib

Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types
Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types

Protected is a Swift Package that allows you to specify the read and write rights for any type, depending on context by using Phantom types

Phiole - Allow to write or read from standards stream or files for script or CLI application

No longer maintained! Phiole - Φole Simple object to wrap three NSFileHandle: 'output', 'error' to write and 'input' to read There is of course a defa

ReadWriteLock - Swift Implementation of a standard Read/Write lock.

ReadWriteLock A Swift implementation of a Read/Write lock. I'm really amazed that the Swift Standard Library (nor the Objective-C standard library) ha

PeekView supports peek, pop and preview actions for iOS devices without 3D Touch capibility
PeekView supports peek, pop and preview actions for iOS devices without 3D Touch capibility

PeekView When implementing peek, pop and preview actions with 3D Touch, you may want to support such features for users accessing your app from older

AmiiboReader - Reading data from amiibo by using Core NFC

AmiiboReader Reading data from amiibo by using Core NFC NTAG215 Data Sheet https

SharePlay-TextEditor - An iOS & iPadOS application, by which people can write/edit texts and change font-styles/background color over FaceTime call Track is a thread safe cache write by Swift. Composed of DiskCache and MemoryCache which support LRU.
Track is a thread safe cache write by Swift. Composed of DiskCache and MemoryCache which support LRU.

Track is a thread safe cache write by Swift. Composed of DiskCache and MemoryCache which support LRU. Features Thread safe: Implement by dispatch_sema

AwaitKit is a powerful Swift library which provides a powerful way to write asynchronous code in a sequential manner.
AwaitKit is a powerful Swift library which provides a powerful way to write asynchronous code in a sequential manner.

AwaitKit is a powerful Swift library inspired by the Async/Await specification in ES8 (ECMAScript 2017) which provides a powerful way to write asynchronous code in a sequential manner.

Write unit tests which test the layout of a view in multiple configurations
Write unit tests which test the layout of a view in multiple configurations

Overview This library enables you to write unit tests which test the layout of a view in multiple configurations. It tests the view with different dat

Xcode plugin which help you write code faster.
Xcode plugin which help you write code faster.

MLAutoReplace Xcode plugin, Re-Intent, make you write code more quickly. Use a portion code of VVDocumenter-Xcode. ##Overview You can use shortcut key

StatusBarOverlay will automatically show a
StatusBarOverlay will automatically show a "No Internet Connection" bar when your app loses connection, and hide it again. It supports apps which hide the status bar and The Notch

StatusBarOverlay StatusBarOverlay will automatically show a "No Internet Connection" bar when your app loses connection, and hide it again. It support

Comments
  • Get UID And Serial Number of the NFC Tag iOS

    Get UID And Serial Number of the NFC Tag iOS

    I'm developing an application in which I want to get the NFC serial number and Identifier of a NFC tag. When I press a button, I want the application to find the UID and serial number of the NFC card. The only problem is that I have no idea how to get the UID and and serial number if that's possible on iOS. I m trying to get NFC identifier but i don't know how to get serial number of NFC Tag.

    Code:-

    class ScanNFCTag: NFCTagReaderSessionDelegate {
    
    import CoreNFC
    
    var session: NFCTagReaderSession?
    
    func scanNFCTag(sender: UIButton!) {
         self.session = NFCTagReaderSession(pollingOption: .iso14443, delegate: self)
         self.session?.alertMessage = "Hold Your Phone Near the NFC Tag"
         self.session?.begin()
    }
    
    func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) {
        print("Session Begin!")
    }
    
    func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) {
        print(error.localizedDescription)
    }
    
    func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
        if tags.count > 1{
            session.alertMessage = "More Than One Tag Detected, Please try again"
            session.invalidate()
        }
        
        let tag = tags.first!
        session.connect(to: tag) { (error) in
            if nil != error{
                session.invalidate(errorMessage: error?.localizedDescription ?? "")
            }
            if case let .miFare(sTag) = tag{
                let UID = sTag.identifier.map{ String(format:"%.2hhx", $0)}.joined()
                session.alertMessage = "Successfully linked tag to location"
                session.invalidate()
                DispatchQueue.main.async {
                    print("NFC Identifer = ", "\(UID)")
                   }
               }
           }
       }
    }
    

    So, Here is the my code please let me know if i m doing wrong please correct me. Can someone please explain to me how to get serial number and UID of NFC tag,

    Any help would be greatly appreciated.

    Thanks in advance.

    opened by shamdass 2
Swipe to "like" or "dislike" any view, just like Tinder.app. Build a flashcard app, a photo viewer, and more, in minutes, not hours!

MDCSwipeToChoose Swipe to "like" or "dislike" any view, just like Tinder.app. Build a flashcard app, a photo viewer, and more, in minutes, not hours!

Brian Gesiak 2.6k Aug 22, 2022
🃏 Cardslider is a design UI controller that allows you to swipe through cards with pictures and accompanying descriptions.

CARD SLIDER UI controller that allows you to swipe through cards with pictures. We specialize in the designing and coding of custom UI for Mobile Apps

Ramotion 1.2k Sep 19, 2022
A reactive, card-based UI framework built on UIKit for iOS developers.

CardParts - made with ❤️ by Intuit: Example Requirements Installation Communication & Contribution Overview Quick Start Architecture CardsViewControll

Intuit 2.4k Sep 12, 2022
A SwiftUI based custom sheet card to show information in iOS application.

A SwiftUI based custom sheet card to show any custom view inside the card in iOS application.

Mahmud Ahsan 4 Mar 28, 2022
A easy-to-use SwiftUI view for Tinder like cards on iOS, macOS & watchOS.

?? CardStack A easy-to-use SwiftUI view for Tinder like cards on iOS, macOS & watchOS. Installation Xcode 11 & Swift Package Manager Use the package r

Deniz Adalar 257 Sep 14, 2022
KolodaView is a class designed to simplify the implementation of Tinder like cards on iOS.

KolodaView Check this article on our blog. Purpose KolodaView is a class designed to simplify the implementation of Tinder like cards on iOS. It adds

Yalantis 5.1k Sep 20, 2022
Awesome iOS 11 appstore cards in swift 5.

Cards brings to Xcode the card views seen in the new iOS XI Appstore. Getting Started Storyboard Go to main.storyboard and add a blank UIView Open the

Paolo Cuscela 4.1k Sep 20, 2022
An iOS library to create beautiful card transitions.

CSCardTransition CSCardTransition is a small library allowing you to create wonderful push and pop transition animations like in the App Store. It wor

Creastel 5 Jan 14, 2022
IOS Card Game - A simple card game using SwiftUI

IOS_Card_Game A simple card game using Swift UI.

Md. Masum Musfique 1 Mar 25, 2022
Easy to read and write chainable animations in Objective-C and Swift

Whats new in version 3.x? Swiftier syntax Swift 4 support Bug fixes and improvements Whats new in version 2.x? Re-architected from the ground up, no m

Jeff Hurray 3.2k Sep 16, 2022