Code Monkey home page Code Monkey logo

nfclib-ios's Introduction

NfcLib-iOS

An easy to use Nfc library for iOS.

Checkout the NFCLib for Android NFC-Android

Setup

pod 'NfcLib'

Add the NFC entitlement to your project

Usage

A simple usage of the library to read from a tag

var readNfc: ReadNfc?

override func viewDidLoad() {
        super.viewDidLoad()
        
        // create readNfc
        readNfc = NfcFactory<ReadNfc>.create(viewController: self)
    
 }
 
 
 func scan() {
  readNfc?.begin() { results in
                // Upon comletion grab the array with the results
                self.handleResults(results: results)
            }
 
 }
 
/**
 Handle the results from NTAG
*/
func handleResults(results: [Any]) {
        for (index, result) in results.enumerated() {
            switch result {
            case is String:
                // Display String
                self.displayResults(index, result: result as! String)
            case is URL:
                // Display URL
                self.displayResults(index, result: result as! URL)
            default:
                // No data :(
                debugPrint("No data :(")
            }
        }
}
    
func displayResults(_ index: Int, result: String) {
     var prevText = resultsTextView.text!
     prevText += "\(index+1). \(result)\n"
     resultsTextView.text = prevText
}
    
func displayResults(_ index: Int, result: URL) {
    var prevText = resultsTextView.text!
    prevText += "\(index+1). \(result.absoluteString)\n"
    resultsTextView.text = prevText
}

A simple usage of the library to write to a tag

var writeNfc: WriteNfc?

override func viewDidLoad() {
        super.viewDidLoad()
        // create writeNfc
        writeNfc = NfcFactory<WriteNfc>.create(viewController: self)
    
}
    
func scan() {
  writeNfc?.begin(message: "Hellom from NFCLib") { result in
         // result is boolean
         if result {
             self.displayResults(0, result: "Writen to tag successfully")
         } else {
              self.displayResults(-1, result: "Error writing to tag!")
         }
  }

}
    

A simple usage of the library to read and write to a tag

Don't do a read after a write operation, remove the NTAG and use the scan session again

var readNfc: ReadNfc?
var writeNfc: WriteNfc?
var readFlag = true

override func viewDidLoad() {
        super.viewDidLoad()
        
        // create readNfc
        readNfc = NfcFactory<ReadNfc>.create(viewController: self)
        // create writeNfc
        writeNfc = NfcFactory<WriteNfc>.create(viewController: self)
    
}

func scan() {
        
        // READ
        if readFlag {
            readNfc?.begin() { results in
                // Upon comletion grab the array with the results
                self.handleResults(results: results)
            }
        
            // End the connection after 2 sec and display the alert for 1 sec
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                // Delay dismissing the alert after showing the message
                self.readNfc?.end(message: "Testing end() function", delay: 1)
            }
            
        } else { // WRITE
            writeNfc?.begin("") { result in
                if result {
                    self.displayResults(0, result: "Writen to tag successfully")
                } else {
                    self.displayResults(-1, result: "Error writing to tag!")
                }
            }
        }
}

License

License

nfclib-ios's People

Contributors

maliotis avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar

nfclib-ios'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.