macos - 使用 swift 或 obj-c 在 cocoa 应用程序 OS X 中读取和写入文件标签

标签 macos cocoa metadata exif

有没有办法在没有 shell 命令的情况下读取/写入文件标签?已经尝试过 NSFileManagerCGImageSource 类。到目前为止还没有运气。

enter image description here

最佳答案

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)
}
<小时/>

Swift 3+ 版本有点不同。在 URL 中,tagNames 属性是仅获取的,因此需要将 URL 桥接转换为 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)
}

关于macos - 使用 swift 或 obj-c 在 cocoa 应用程序 OS X 中读取和写入文件标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38633600/

相关文章:

objective-c - 安装后应用程序无法正常运行

objective-c - 模态表窗口未居中

macos - 根据 contentView 的新大小调整 NSWindow 的大小

swift - 单击 StatusBar 项目时弹出一个 View

python - 如何在 Mac OS X 上安装密码学?

java - 如何获取WiFi网络接口(interface)的MAC地址?

cocoa - activeProcessorCount 和processorCount 之间有什么区别?

javascript - 获取/设置谷歌云存储中的元数据 - node.js

postgresql - postgresql 的 jdbc 驱动程序的 "ResultSet.getMetaData.getTableName(col)"总是返回一个空字符串是否正确?

python - 使用 Python 从 radio 流中读取 SHOUTcast/Icecast 元数据