Read UID from NFC mifare tag iOS 13
Asked Answered
A

1

2

I'm trying to read the UID for a mifare tag.

Looking at examples, I see the following method a lot:

func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {      
  if case let NFCTag.miFare(tag) = tags.first! {
    print(tag.identifier as NSData)
  }
}

However when putting that into my project, the method is not called.

I also noticed xCode giving a warning that this nearly matches an optional protocol which is the same except it uses NFCNDEFTag instead of NFCTag..

When I try update to that,that method does get called. But then I'm having trouble trying to define the tag as mifare inside that method. I get the error 'Pattern cannot match values of type 'NFCNDEFTag'.

Code below:

    @available(iOS 13.0, *)
    func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCNDEFTag]) {
        print("in did detect tags")

        let tag = tags.first!

        session.connect(to: tag) { (error: Error?) in


            session.connect(to: tag) { (error: Error?) in
                   if case let .mifare(mifareTag) = tag {
                       // can access tag identifier here?

                    }
            }
        }
    }
Aitken answered 8/10, 2019 at 11:23 Comment(0)
T
0

This is how I achieved it:

func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag] {
    let tag = tags.first!
    readerSession?.connect(to: tag, completionHandler: { error in
        if case let .miFare(miFare) = tag {
            var byteData = [UInt8]()
            miFare.identifier.withUnsafeBytes { byteData.append(contentsOf: $0) }
            var uid = "0"
            byteData.forEach {
                uid.append(String($0, radix: 16))
            }
            print("UID: \(uid)")
        }
    })
}
Teratism answered 4/9, 2020 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.