Is there any way to read/write file tags without shell commands? Already tried NSFileManager
and CGImageSource
classes. No luck so far.
Asked
Active
Viewed 2,064 times
2 Answers
7
An NSURL
object has a resource for key NSURLTagNamesKey
. The value is an array of strings.
This Swift example reads the tags, adds the tag Foo
and write the tags back.
let url = NSURL(fileURLWithPath: "/Path/to/file.ext")
var resource : AnyObject?
do {
try url.getResourceValue(&resource, forKey: NSURLTagNamesKey)
var tags : [String]
if resource == nil {
tags = [String]()
} else {
tags = resource as! [String]
}
print(tags)
tags += ["Foo"]
try url.setResourceValue(tags, forKey: NSURLTagNamesKey)
} catch let error as NSError {
print(error)
}
The Swift 3+ version is a bit different. In URL
the tagNames
property is get-only so it's necessary to bridge cast the URL
to Foundation NSURL
var url = URL(fileURLWithPath: "/Path/to/file.ext")
do {
let resourceValues = try url.resourceValues(forKeys: [.tagNamesKey])
var tags : [String]
if let tagNames = resourceValues.tagNames {
tags = tagNames
} else {
tags = [String]()
}
tags += ["Foo"]
try (url as NSURL).setResourceValue(tags, forKey: .tagNamesKey)
} catch {
print(error)
}

vadian
- 274,689
- 30
- 353
- 361
-
Great! you helped a lot. Thanks. – arsena Jul 28 '16 at 11:13
-
Hello again. Is there any method to remove an existing tag? like removeResourceValue or something? – arsena Sep 01 '16 at 08:53
-
1Use `setResourceValue` with an empty array or if you want to keep others remove the value from the array and write it back. – vadian Sep 01 '16 at 08:55
3
@vadian's answer in Swift 4.0
('NSURLTagNamesKey' has been renamed to 'URLResourceKey.tagNamesKey'
)
let url = NSURL(fileURLWithPath: "/Path/to/file.ext")
var resource : AnyObject?
do {
try url.getResourceValue(&resource, forKey: URLResourceKey.tagNamesKey)
var tags : [String]
if resource == nil {
tags = [String]()
} else {
tags = resource as! [String]
}
print(tags)
tags += ["Foo"]
try url.setResourceValue(tags, forKey: URLResourceKey.tagNamesKey)
} catch let error as NSError {
print(error)
}