How to read file comment field

后端 未结 2 938
终归单人心
终归单人心 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)
                }
            }
        }
    }
    

提交回复
热议问题