如何向iOS上的NFC标签发送自定义命令?

fivyi3re  于 2023-02-14  发布在  iOS
关注(0)|答案(1)|浏览(259)

我有一个符合ISO 14443 - 4格式的标签,我需要发送一个十六进制命令30 4F(读块79)给它,我该怎么做?我正在尝试使用NFCTagReaderSessiontagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]),但我不知道如何发送一个十六进制命令与它,和官方文档没有帮助.
谢谢大家!

wz3gfoph

wz3gfoph1#

我的ISO-1443 NTAG 213 TT标签(带有防篡改封条)被NFCTagReaderSession检测为NFCMiFareFamily.unknown类型的MiFare标签。我可以使用NFC工具应用程序发送“30 01”命令,但我需要能够在代码中执行相同的操作。起作用的是sendMiFareCommand方法。我在下面发布了一个片段:

func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
    guard let firstTag = tags.first else { return }
    session.connect(to: firstTag) { (error: Error?) in
        if error != nil {
            session.invalidate(errorMessage: "Connection error. Please try again.")
            return
        }

        print("Connected to a tag!")

        if case let .miFare(miFareTag) = tag {
            let hexCommand: [UInt8] = [0x30, 0x01]     // 30 01 hex command
            if #available(iOS 14, *) {
                miFareTag.sendMiFareCommand(commandPacket: Data(hexCommand)) { (result: Result<Data, Error>) in
                    switch result {
                    case .success(let response):
                        let hexResponse: [String] = response.map { String(format: "%02x", $0) }   // make an array of hex strings
                        if hexResponse.count == 16 {
                            let firstTamperBlock = hexResponse[3] // e.g. "4f"
                            let secondTamperBlock = hexResponse[4]  // e.g. "00"

                            // you can inspect any block in the response by accessing hexResponse array elements
                        }
                    case .failure(let error):
                        print("Read tag error: \(error.localizedDescription)")
                        completion(nil)
                    }
                }
            } else {
                miFareTag.sendMiFareCommand(commandPacket: Data(hexCommand)) { (response: Data, optionalError: Error?) in
                    guard let error = optionalError else {
                        print("response: \(response)")
                        return
                    }
                    print("Read tag error: \(error.localizedDescription)")

                }
            }
        } else {
            fatalError("Tag wasn't recognized as MiFare")
        }
    }
}

我最初认为我需要使我的标记能够被识别为.iso7816类型,以便成功地发送任何命令,但事实并非如此,我也不必向plist添加任何AID(应用程序标识符)。

相关问题