该库通过扩展 URL
结构体来处理文件扩展属性。
首先,您必须从 Github 克隆此项目
git clone https://github.com/amosavian/ExtendedAttributes
然后,您可以手动安装,将 Sources/ExtendedAttributes
目录添加到您的项目,或者创建一个 xcodeproj
文件并将其作为动态框架添加。
swift package generate-xcodeproj
扩展属性仅适用于以 file:///
开头的 URL。
要获取为文件设置了哪些扩展属性
do {
print(try url.listExtendedAttributes())
} catch {
print(error.localizedDescription)
}
要检查特定扩展属性是否存在
if url.hasExtendedAttribute(forName: "eaName") {
// Do something
}
要检索扩展属性的原始数据,只需使用以下代码作为模板。 请注意,如果扩展属性不存在,它将抛出一个错误。
do {
let data = try url.extendedAttribute(forName: "eaName")
print(data as NSData)
} catch {
print(error.localizedDescription)
}
如果扩展属性以标准 plist 二进制格式设置,则可以检索它们的值。 这可以是 String
、Int
/NSNumber
、Double
、Bool
、URL
、Date
、Array
或 Dictionary
。 数组不应包含 nil
值。
要检索扩展属性的原始数据,只需使用以下代码作为模板
do {
let notes: String = try url.extendedAttributeValue(forName: "notes")
print("Notes:", notes)
let isDownloeded: Bool = try url.extendedAttributeValue(forName: "isdownloaded")
print("isDownloaded:", isDownloeded)
let originURL: URL = try url.extendedAttributeValue(forName: "originurl")
print("Original url:", originurl)
} catch {
print(error.localizedDescription)
}
或者列出文件的所有值
do {
for name in try url.listExtendedAttributes() {
let value = try url.extendedAttributeValue(forName: name)
print(name, ":" , value)
}
} catch {
print(error.localizedDescription)
}
要为扩展属性设置原始数据
do {
try url.setExtendedAttribute(data: Data(bytes: [0xFF, 0x20]), forName: "data")
} catch {
print(error.localizedDescription)
}
要为扩展属性设置值
do {
let dictionary: [String: Any] = ["name": "Amir", "age": 30]
try url.setExtendedAttribute(value: dictionary, forName: "identity")
} catch {
print(error.localizedDescription)
}
要移除扩展属性
do {
try url.removeExtendedAttribute(forName: "identity")
} catch {
print(error.localizedDescription)
}
查看 Issues 页面。
我们希望您能为 ExtendedAttributes 做出贡献,请查看 LICENSE 文件以获取更多信息。