ExtendedAttributes
This library handles file extended attributes by extending URL
struct.
Requirements
- Swift 4.0 or higher
- macOS, iOS, tvOS or Linux
- XCode 9.0
Installation
First you must clone this project from github:
git clone https://github.com/amosavian/ExtendedAttributes
Then you can either install manually by adding Sources/ExtendedAttributes
directory to your project
or create a xcodeproj
file and add it as a dynamic framework:
swift package generate-xcodeproj
Usage
Extended attributes only work with urls that begins with file:///
.
Listing
To get which extended attributes are set for file:
do {
print(try url.listExtendedAttributes())
} catch {
print(error.localizedDescription)
}
Retrieving
To check either a specific extended attribute exists or not:
if url.hasExtendedAttribute(forName: "eaName") {
// Do something
}
To retrieve raw data for an extended attribute, simply use this code as template, Please note if extended attribute doesn't exist, it will throw an error.
do {
let data = try url.extendedAttribute(forName: "eaName")
print(data as NSData)
} catch {
print(error.localizedDescription)
}
You can retrieve values of extended attributes if they are set with standard plist binary format. This can be String
, Int
/NSNumber
, Double
, Bool
, URL
, Date
, Array
or Dictionary
. Arrays should not contain nil
value.
To retrieve raw data for an extended attribute, simply use this code as template:
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)
}
or to list all values of a file:
do {
for name in try url.listExtendedAttributes() {
let value = try url.extendedAttributeValue(forName: name)
print(name, ":" , value)
}
} catch {
print(error.localizedDescription)
}
Setting attributes
To set raw data for an extended attribute:
do {
try url.setExtendedAttribute(data: Data(bytes: [0xFF, 0x20]), forName: "data")
} catch {
print(error.localizedDescription)
}
To set a value for an extended attribute:
do {
let dictionary: [String: Any] = ["name": "Amir", "age": 30]
try url.setExtendedAttribute(value: dictionary, forName: "identity")
} catch {
print(error.localizedDescription)
}
Removing
To remove an extended attribute:
do {
try url.removeExtendedAttribute(forName: "identity")
} catch {
print(error.localizedDescription)
}
Known issues
Check Issues page.
Contribute
We would love for you to contribute to ExtendedAttributes, check the LICENSE file for more info.