Git Product home page Git Product logo

janlionly / nfcreaderwriter Goto Github PK

View Code? Open in Web Editor NEW
133.0 1.0 25.0 412 KB

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. I will appreciate you if give me a star on the top right of page.

Home Page: https://github.com/janlionly/NFCReaderWriter

License: MIT License

Swift 100.00%
nfc-card-reader nfc-tag nfc-writer nfc-chips nfc-reader nfc-library nfc corenfc ntag ntag424

nfcreaderwriter's Introduction

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.

nfcreaderwriter's People

Contributors

janlionly avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

nfcreaderwriter's Issues

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.