NdefLibrary
描述
非接触式智能卡数据交换格式(NDEF)规定了符合NFC论坛规范的设备及其标签的通用数据格式。该规范的1.0版本可以在这里找到。[1]
该库旨在用于需要从外部NFC读取器(如TapTrack Tappy读取器)中验证、解析和合成NDEF消息的应用程序。
此库支持以下记录类型的NDEF消息
- 文本记录
- URI记录
- 通用记录
使用CocoaPods安装
pod 'NdefLibrary'
如何使用
创建记录
文本记录
您可以通过指定文本编码类型、语言代码和文本来创建文本记录。
let encoding = TextRecord.TextEncodingType.Utf8
let languageCode : String = "en"
let text : String = "hello world!"
// Construct the text record.
let textRecord = Ndef.CreateTextRecord(textEncoding: encoding, languageCode: languageCode, text: text)
您可以通过向CreateNdefMessage
方法传递原始字节数组来从原始字节数组创建TextRecord(参见下面的解析消息)。
URI记录
您可以通过指定URI字符串来创建URI记录。
let githubUrl = "https://www.github.com/"
// Construct the URI record.
let uriRecord = Ndef.CreateUriRecord(uri: githubUrl)
您还可以通过将原始字节数组传递到CreateNdefMessage
方法来从原始字节数组创建UriRecord(参见下面的解析消息)。
通用记录
要创建任何其他类型的记录,您可以使用GenericRecord
对象。您需要指定类型名称格式、记录类型和有效载荷。
let tnf = Ndef.TypeNameFormat.external
let recordType : [UInt8] = [0x74, 0x65, 0x73, 0x74]
let recordPayload : [UInt8] = [0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d]
// Construct a custom NDEF record. This method will return nil if the payload is invalid.
let customRecord = Ndef.CreateGenericRecord(tnf: tnf, type: recordType, payload: recordPayload)
创建NDEF消息
您可以通过指定一系列记录来构建NDEF消息。
let myRecords : [NdefRecord] = [record1, record2, record3]
// Construct an NDEF message.
let message = Ndef.CreateNdefMessage(records: myRecords)
您还可以通过调用实例方法toByteArray()
将NdefMessage
对象转换为原始字节数组。
let rawMessage = message.toByteArray()
解析原始NDEF消息
您可以通过将原始字节数组传递给MessageBox
方法CreateNdefMessage(rawByteArray: [UInt8])
来解析原始NDEF消息。它将返回一个包含NDEF记录数组的NdefMessage
对象,您可以通过records
字段来访问它们。
注意:目前不支持分块记录。CreateNdefMessage
方法在遇到设置了分块标志的记录时将返回nil
。
// Empty NDEF record for example purposes.
let rawNdefMessage : [UInt8] = [0xD0, 0x00, 0x00]
// Construct an NdefMessage from a raw byte array. If the raw byte array does
// not represent a valid, complete NDEF message, this method will return nil.
let message = Ndef.CreateNdefMessage(rawByteArray: rawNdefMessage)
// Unwrap the message and get the array of records.
var records : [NdefRecord] = []
if let unwrappedMsg = message {
records = unwrappedMsg.records
}
然后您可以访问每个记录的字段。
// Print out the TNF, type, and payload of each record in the NDEF message.
for record in records {
print("Type Name Format: \(record.tnf)")
print("Type: \(record.type)")
print("Payload: \(record.payload)")
}
要访问特定于记录的字段,您需要进行类型转换。
// Get the contents of a TextRecord by downcasting.
if let textRecord = records[0] as? TextRecord {
let encoding = textRecord.textEncoding
let language = textRecord.languageCode
let text = textRecord.text
}
// Get the contents of a UriRecord by downcasting.
if let uriRecord = records[1] as? UriRecord {
let uriString = uriRecord.uri
}
可选返回值
注意,某些记录构建方法将返回必须在使用前解包的可选值。下面是解包的示例。您也可以参考官方Swift文档获取更详细的说明。
贡献者
作者:Alice Cai
库由TapTrack维护([email protected])。
许可
NdefLibrary在MIT许可下提供。有关更多信息,请参阅LICENSE文件。
注释
[1] 此链接可能无法保留,因为NFC论坛仅向付费成员提供其规范的有限访问,并且可能将此页面删除。