如何从 Swift 编写 Finder 注释

问题描述 投票:0回答:1

按照 另一个答案 中的代码,我想读取 Finder 注释并将其写入文件。这些似乎存储为二进制 plist,因此必须事先对其进行解析。要阅读 Finder 评论:

let fileURL = URL(fileURLWithPath: "/path/to/file")

guard let commentData = try? fileURL.extendedAttribute(forName: "com.apple.metadata:kMDItemFinderComment"),
      let commentString = try? PropertyListSerialization.propertyList(from: commentData, options: [], format: nil) as? String
else { fatalError("Could not get comment") }

print(commentString)

效果很好。但到目前为止我还没有正确编写字符串。最接近的是:

let fileURL = URL(fileURLWithPath: "/path/to/file")
let comment = "This is a Finder comment"

do {
  let plistData = try PropertyListSerialization.data(fromPropertyList: comment, format: .binary, options: 0)
  try fileURL.setExtendedAttribute(data: plistData, forName: "com.apple.metadata:kMDItemFinderComment")
} catch {
  fatalError("Could not write comment")
}

虽然这似乎有效并且可以通过上述方法读回注释,但更改不会反映在 Finder 中的文件中,或者通过

mdls
查看属性时。

swift macos finder xattr
1个回答
0
投票

您尝试过使用

setxattr
吗?

这是一个粗略的例子:

var path = "my.file"

var attrName = "com.apple.metadata:kMDItemFinderComment"
let attrValue = "my comment".data(using: .utf8)!

if (setxattr(path, attrName, (attrValue as NSData).bytes, attrValue.count, 0, 0) == -1) {
    perror("setxattr failed")
}
© www.soinside.com 2019 - 2024. All rights reserved.