XAttr

XAttr 让使用扩展文件属性成为 Foundation 的自然组成部分。NSURLNSFileHandle 对象都获得了使用与 Cocoa 非常匹配的 API 读取和写入扩展属性的能力。将元数据的强大功能添加到您的应用程序!

适用于 iOS、macOS、watchOS 和 tvOS。

有关 Darwin 的扩展属性 API(这是此模块的基础)的更多信息,请参阅 Apple 的 man 页面:listxattrgetxattrsetxattrremovexattr

示例

这是一个使用文件 URL 处理扩展属性的简单示例

import XAttr

let myURL = URL(fileURLWithPath: "/path/to/file")

let data = "value".data(using: .utf8)!

// Set an attribute
try myURL.setExtendedAttribute(name: "com.example.attribute", value: data)
// List attributes
let names = try myURL.extendedAttributeNames()
// Get an attribute's value
let value = try myURL.extendedAttributeValue(forName: "com.example.attribute")
// Remove an attribute
try myURL.removeExtendedAttribute(forName: "com.example.attribute")

// Set multiple attributes
try myURL.setExtendedAttributes(attrs: ["com.example.attribute1": data, "com.example.attribute2": data])
// Get multiple attributes' values (all available)
let attrs = try myURL.extendedAttributeValues(forNames: nil)
// Remove multiple attributes (all)
try myURL.removeExtendedAttributes(forNames: nil)

安装

需要 Swift 5.7。

Swift Package Manager

将 XAttr 作为依赖项添加到您的项目中

// Package.swift

import PackageDescription

let package = Package(
    name: "YourProjectName",
    dependencies: [
        .package(url: "https://github.com/jozefizso/swift-xattr", majorVersion: 3),
    ]
)

用法

XAttr 易于使用。本节包含所有所需的基本信息。请务必查看 Xcode 中的快速帮助以获取更多详细信息。

方法

以下方法适用于 URLFileHandle 对象

检索属性的值

extendedAttributeValue(forName: String, options: XAttrOptions = []) throws -> Data

检索多个属性的值

extendedAttributeValues(forNames: [String]?, options: XAttrOptions = []) throws -> [String: Data]

提供要检索的名称列表,或 nil 以检索所有可用的属性。

设置属性的值

setExtendedAttribute(name: String, value: Data, options: XAttrOptions = []) throws

设置多个属性的值

setExtendedAttributes(attrs: [String: Data], options: XAttrOptions = []) throws

提供要设置在目标上的 name:value 对的字典。

列出属性名称

extendedAttributeNames(options: XAttrOptions = []) throws -> [String]

移除扩展属性

removeExtendedAttribute(forName: String, options: XAttrOptions = []) throws

移除多个扩展属性

removeExtendedAttributes(forNames: [String]?, options: XAttrOptions = []) throws

提供要移除的名称列表,或 nil 以移除所有现有的属性。

选项

XAttrOptions 提供以下选项

选项 描述 获取 设置 列出 移除
NoFollow 不要跟随符号链接。 x x x x
CreateOnly 如果指定的属性已存在,则失败。 x
ReplaceOnly 如果指定的属性尚不存在,则失败。 x
ShowCompression 显示或移除 HFS+ 压缩扩展属性。 x x x

注意: 如果未指定 CreateOnlyReplaceOnly,则无论其当前状态如何,都将创建/更新属性。

错误

如果系统无法获取/设置/列出/移除扩展属性,将抛出一个 NSError。该错误将具有 Foundation 内置的 NSPOSIXErrorDomain。错误的 code 属性将表示系统报告的 POSIX 错误代码,错误的 localizedDescription 属性将包含对错误的解释。

此外,如果系统能够检索属性的名称,但无法对其进行解码,则将抛出一个 NSError,其 Foundation 内置的NSCocoaErrorDomaincodeNSFileReadInapplicableStringEncodingError

最后,如果在获取/设置/移除多个扩展属性时遇到错误,则导致错误的特定属性将在错误的 userInfo 字典中命名,键为 ExtendedAttributeNameKey

许可证

XAttr 在宽松的 ISC 许可证下获得许可。
XAttr 是 Foundation-XAttr 存储库的一个分支。

Copyright (c) 2016, Justin Pawela 和贡献者 Copyright © 2023 Cisco Systems, Inc.