Reading UIDs of NFC Cards in iOS 13

后端 未结 3 1781
一整个雨季
一整个雨季 2020-12-16 19:47

I would like to retrive the UID of MiFare cards. I\'m using an iPhone X, Xcode 11 and iOS 13.

I\'m aware this wasn\'t possible (specifically reading the UID) until

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 20:28

    Ok I have an answer.

    tag.identifier isn't empty -- per se -- if you examine from Xcodes debugger it appears empty (0x00 is the value!). It's type is Data and printing it will reveal the length of the Data but not how it's encoded. In this case it's a [UInt8] but stored as a bag of bits, I don't understand why Apple have done it this way -- it's clunky -- I'm sure they have good reasons. I would have stored it as a type String -- after all the whole point of a high level language like Swift is to abstract us away from such hadware implementation details.

    The following code will retrive the UID from a MiFare card:

    if case let NFCTag.miFare(tag) = tags.first! {
        session.connect(to: tags.first!) { (error: Error?) in
            let apdu = NFCISO7816APDU(instructionClass: 0, instructionCode: 0xB0, p1Parameter: 0, p2Parameter: 0, data: Data(), expectedResponseLength: 16)
            tag.sendMiFareISO7816Command(apdu) { (apduData, sw1, sw2, error) in
                let tagUIDData = tag.identifier
                var byteData: [UInt8] = []
                tagUIDData.withUnsafeBytes { byteData.append(contentsOf: $0) }
                var uidString = ""
                for byte in byteData {
                    let decimalNumber = String(byte, radix: 16)
                    if (Int(decimalNumber) ?? 0) < 10 { // add leading zero
                        uidString.append("0\(decimalNumber)")
                    } else {
                        uidString.append(decimalNumber)
                    }
                }
                debugPrint("\(byteData) converted to Tag UID: \(uidString)")
            }
        }
    }
    

提交回复
热议问题