9.5 C
New York
Monday, November 18, 2024

ios – How can I fetch knowledge from a Vigik badge (ISO/IEC 7816-5:2004) utilizing Core NFC?


I am engaged on an app that makes use of Core NFC to detect NFC playing cards, and every part is working fantastic with different playing cards comparable to MIFARE or ISO 14443 tags. Nonetheless, I am having hassle detecting the Vigik badge particularly. I’ve registered the AID for the Vigik badge appropriately in my app’s Entitlements.plist, however after I scan the badge, it doesn’t get detected, although different playing cards are working as anticipated.

Listed below are some particulars about my implementation:

  1. AID Registration: I’ve registered the right AID for the Vigik badge within the entitlements file, and the right tag kind is being polled utilizing NFCTagReaderSession.
  2. Different Playing cards Detected: NFC playing cards like ISO 14443 and MIFARE are being detected and skim appropriately.
//
//  ViewController.swift
//  testNFCCOre
//
//  Created by thoughts on 12/11/24.
//

import UIKit
import CoreNFC

class ViewController: UIViewController, NFCTagReaderSessionDelegate {
    var nfcSession: NFCReaderSession?

    override func viewDidLoad() {
        tremendous.viewDidLoad()
    }
    
    @IBAction func onTapScan(_ sender: Any) {
        startScanning()
    }
    
    func startScanning() {
        guard NFCTagReaderSession.readingAvailable else {
            print("NFC is just not supported on this machine.")
            return
        }
        
        // Create a session for uncooked tag studying
        nfcSession = NFCTagReaderSession(pollingOption: [.iso14443,.iso18092,.iso15693], delegate: self, queue: DispatchQueue.major)
        
        // Start the session
        nfcSession?.start()
    }
    
    // Referred to as when the session turns into lively
    func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) {
        print("NFC session is lively.")
        // You'll be able to inform the person that the NFC reader is lively or present a message
    }
    
    // Referred to as when the session is invalidated (e.g., person cancels or an error happens)
    func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: Error) {
        if let error = error as? NFCReaderError {
            change error.code {
            case .readerSessionInvalidationErrorUserCanceled:
                print("Person canceled the session.")
            case .readerSessionInvalidationErrorSessionTimeout:
                print("Session timed out.")
            case .readerSessionInvalidationErrorSystemIsBusy:
                print("System is busy. Please attempt once more.")
            default:
                print("Session invalidated with error: (error.localizedDescription)")
            }
        } else {
            print("Session invalidated with error: (error.localizedDescription)")
        }
    }
    
    // Referred to as when the session detects NFC tags
    func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
        let tag = tags.first!
        session.join(to: tag) { error in
            if let error = error {
                print("Connection failed: (error.localizedDescription)")
                return
            }
            print("Tag related efficiently!")
            
            // Proceed processing the tag relying on its kind
            for tag in tags {
                change tag {
                case .miFare(let mifareTag):
                    print("MIFARE tag detected: (mifareTag)")
                    self.handleMifareTag(mifareTag)
                    
                case .feliCa(let feliCaTag):
                    print("FeliCa tag detected: (feliCaTag)")
                    self.handleFeliCaTag(feliCaTag)
                    
                case .iso7816(let iso7816Tag):
                    print("ISO 7816 tag detected: (iso7816Tag)")
                    
                    let aidData = Information([
                        0xA0, 0x00, 0x00, 0x00, 0x86, 0x32, 0x05, 0x49,
                        0x47, 0x49, 0x4B, 0xAE, 0x5F, 0x33
                    ])

                    // Create APDU SELECT command
                    let command = NFCISO7816APDU(
                        instructionClass: 0x00,
                        instructionCode: 0xA4,
                        p1Parameter: 0x04,
                        p2Parameter: 0x00,
                        knowledge: aidData,
                        expectedResponseLength: -1
                    )

                    // Ship the APDU command
                    iso7816Tag.sendCommand(apdu: command) { response, sw1, sw2, error in
                        if let error = error {
                            print("Error sending APDU: (error.localizedDescription)")
                            return
                        }
                        
                        // Parse the response
                        print("Response: (response)")
                        print("Standing phrases: SW1=(sw1), SW2=(sw2)")
                        
                        // Course of particular utility template if wanted
                        if sw1 == 0x90 && sw2 == 0x00 {
                            print("Utility chosen efficiently!")
                        } else {
                            print("Utility choice failed with standing phrases (sw1), (sw2)")
                        }
                    }


                    self.handleIso7816Tag(iso7816Tag)
                    
                    
                case .iso15693(let nfcATag):
                    print("ISO 15693 tag detected: (nfcATag)")
                    self.handleNfcATag(nfcATag)
                    
                default:
                    print("Unknown tag kind detected.")
                }
            }
            session.invalidate()
        }
    }
    
    // Deal with MIFARE tag
    func handleMifareTag(_ mifareTag: NFCMiFareTag) {
        // Course of MIFARE tag knowledge
        print("MIFARE UID: (mifareTag.identifier)")
    }
    
    // Deal with FeliCa tag
    func handleFeliCaTag(_ feliCaTag: NFCFeliCaTag) {
        // Print accessible info from NFCFeliCaTag
        print("FeliCa tag detected.")
    }
    
    // Deal with ISO 7816 tag (sensible playing cards)
    func handleIso7816Tag(_ iso7816Tag: NFCISO7816Tag) {
        // Course of ISO 7816 tag knowledge
        print("Tag Identifier: (iso7816Tag.identifier.hexString())")
        let hexString = "4a6f686e"  // Hex for "John"
        if let decodedText = hexStringToText(hexString: iso7816Tag.identifier.hexString()) {
            print("Decoded textual content: (decodedText)")  // Outputs: John
        }
        print("Utility Information: (String(describing: iso7816Tag.applicationData))")
        print("Historic Bytes: (String(describing: iso7816Tag.historicalBytes))")
        if let historicalBytes = iso7816Tag.historicalBytes {
            let hexString = historicalBytes.map { String(format: "%02hhx", $0) }.joined()
            print("Historic Bytes as Hex: (hexString)")
        }
        print("Chosen AID: (iso7816Tag.initialSelectedAID)")
    }
    
    // Deal with NFC-A tag
    func handleNfcATag(_ nfcATag: NFCISO15693Tag) {
        // Course of NFC-A tag knowledge
        print("NFC-A UID: (nfcATag.identifier)")
    }
    
    // Convert Hex String to Textual content
    func hexStringToText(hexString: String) -> String? {
        var hex = hexString
        var knowledge = Information()
        whereas hex.rely > 0 {
            let c = hex.prefix(2)
            hex = String(hex.dropFirst(2))
            if let byte = UInt8(c, radix: 16) {
                knowledge.append(byte)
            }
        }
        return String(knowledge: knowledge, encoding: .utf8)
    }
}

// Convert Information to Hex String
extension Information {
    func hexString() -> String {
        return self.map { String(format: "%02hhx", $0) }.joined()
    }
    
    func hexStringToData(hexString: String) -> Information? {
        var knowledge = Information()
        // Make sure the hex string is in legitimate kind (even size)
        let cleanedHexString = hexString.replacingOccurrences(of: " ", with: "").uppercased()
        // Course of each pair of characters (every byte)
        var startIndex = cleanedHexString.startIndex
        whereas startIndex < cleanedHexString.endIndex {
            let endIndex = cleanedHexString.index(startIndex, offsetBy: 2)
            let hexPair = String(cleanedHexString[startIndex..

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles