使用swift或obj-c在Cocoa App OS X中读取和写入文件标签

ars*_*ena 5 macos cocoa exif metadata

没有外壳命令,有没有办法读写文件标签?已经尝试过NSFileManager和CGImageSource上课。到目前为止没有运气。

在此处输入图片说明

vad*_*ian 5

一个NSURL对象具有关键的资源NSURLTagNamesKey。该值是一个字符串数组。

这个Swift示例读取标签,添加标签Foo并写回标签。

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)
}
Run Code Online (Sandbox Code Playgroud)

Swift 3+版本有所不同。在URL该tagNames属性中,该属性是get-only,因此有必要将Cast转换URL为FoundationNSURL

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)
}
Run Code Online (Sandbox Code Playgroud)