Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read file comment field

In OS X Finder there is 'Comment' file property. It can be checked in finder by adding 'Comment' column or edited/checked after right clicking on file or folder and selecting 'Get info'.

How to read this value in swift or objective-c?

I checked already NSURL and none of them seems to be the right ones

like image 651
patmar Avatar asked Jan 10 '16 21:01

patmar


People also ask

What is file Comment?

File Comments (documents) SPSS. Resources ? Back. SPSS Data files may contain comments, i.e. a document of any length that can be used to describe the contents of the file and to any useful information a user might need to understand in order to use the file and it's variables correctly.

Can you add comments to a file?

Right-click the selected file(s) and choose Properties to open the File Properties dialog. 3. Select the Comment tab.


2 Answers

Do not use the low-level extended attributes API to read Spotlight metadata. There's a proper Spotlight API for that. (It's called the File Metadata API.) Not only is it a pain in the neck, there's no guarantee that Apple will keep using the same extended attribute to store this information.

Use MDItemCreateWithURL() to create an MDItem for the file. Use MDItemCopyAttribute() with kMDItemFinderComment to obtain the Finder comment for the item.

like image 101
Ken Thomases Avatar answered Oct 01 '22 03:10

Ken Thomases


Putting the pieces together (Ken Thomases reading answer above and writing answer link) you can extend URL with a computed property with a getter and a setter to read/write comments to your files:

update: Xcode 8.2.1 • Swift 3.0.2

extension URL {
    var finderComment: String? {
        get {
            guard isFileURL else { return nil }
            return MDItemCopyAttribute(MDItemCreateWithURL(kCFAllocatorDefault, self as CFURL), kMDItemFinderComment) as? String
        }
        set {
            guard isFileURL, let newValue = newValue else { return }
            let script = "tell application \"Finder\"\n" +
                String(format: "set filePath to \"%@\" as posix file \n", absoluteString) +
                String(format: "set comment of (filePath as alias) to \"%@\" \n", newValue) +
            "end tell"
            guard let appleScript = NSAppleScript(source: script) else { return }
            var error: NSDictionary?
            appleScript.executeAndReturnError(&error)
            if let error = error {
                print(error[NSAppleScript.errorAppName] as! String)
                print(error[NSAppleScript.errorBriefMessage] as! String)
                print(error[NSAppleScript.errorMessage] as! String)
                print(error[NSAppleScript.errorNumber] as! NSNumber)
                print(error[NSAppleScript.errorRange] as! NSRange)
            }
        }
    }
}
like image 33
Leo Dabus Avatar answered Oct 01 '22 03:10

Leo Dabus