How to write comment into File's metadata from Swift
Asked Answered
M

1

7

Following the code from another answer, I want to read and write Finder comments to files. Those seem to be stored as binary plists so they have to be parsed beforehand. To read a Finder comment:

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)

Which works fine. But I’m so far failing to correctly write a string. The closest was:

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")
}

While this seems to work and the comment can be read back by the method above, the change is not reflected in the file in the Finder, or when viewing the attribute via mdls.

Monto answered 12/12, 2023 at 23:20 Comment(3)
AppleScript works.Chiastolite
Related: #66559090Meng
I know how to do it in AppleScript; I specifically need Swift for this.Monto
C
-1

Have you tried using setxattr?

Here's a rough example:

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")
}
Cassilda answered 18/4 at 0:13 Comment(1)
That doesn’t work. setattr is what the linked answer (whose this uses) is using too.Monto

© 2022 - 2024 — McMap. All rights reserved.