How to write Finder comment from Swift

58 views Asked by At

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.

0

There are 0 answers