How to read file comment field

后端 未结 2 935
终归单人心
终归单人心 2021-01-13 14:18

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 sele

相关标签:
2条回答
  • 2021-01-13 14:49

    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)
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-13 14:56

    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.

    0 讨论(0)
提交回复
热议问题