Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read & Write file tag in cocoa app OS X with swift or obj-c

Is there any way to read/write file tags without shell commands? Already tried NSFileManager and CGImageSource classes. No luck so far.

enter image description here

like image 596
arsena Avatar asked Jul 28 '16 10:07

arsena


1 Answers

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)
}
like image 63
vadian Avatar answered Nov 05 '22 11:11

vadian