Objective c 如何读取文件注释字段
在OSX Finder中有“Comment”文件属性。右键单击文件或文件夹并选择“获取信息”后,可以在finder中添加“注释”列或编辑/检查该文件。 如何在swift或objective-c中读取该值?Objective c 如何读取文件注释字段,objective-c,swift,macos,Objective C,Swift,Macos,在OSX Finder中有“Comment”文件属性。右键单击文件或文件夹并选择“获取信息”后,可以在finder中添加“注释”列或编辑/检查该文件。 如何在swift或objective-c中读取该值? 我已经检查了NSURL,其中似乎没有一个是正确的不要使用低级扩展属性API来读取Spotlight元数据。有一个合适的聚光灯API。(它被称为文件元数据API。)这不仅令人头痛,也不能保证苹果会继续使用相同的扩展属性来存储这些信息 使用MDItemCreateWithURL()为文件创建M
我已经检查了NSURL,其中似乎没有一个是正确的不要使用低级扩展属性API来读取Spotlight元数据。有一个合适的聚光灯API。(它被称为文件元数据API。)这不仅令人头痛,也不能保证苹果会继续使用相同的扩展属性来存储这些信息
使用
MDItemCreateWithURL()
为文件创建MDItem
。使用MDItemCopyAttribute()
和kMDItemFinderComment
获取该项的查找注释。将这些片段放在一起(Ken Thomases读取上面的答案和写入答案)可以使用计算属性扩展URL,并使用getter和setter读取/写入文件的注释:
更新: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)
}
}
}
}
我已经测试过这个解决方案,它适用于大多数文件/文件夹。唯一不起作用的情况是根文件夹。添加到根位置的应用程序、用户、系统等文件夹中的注释在FInder中可见,但在使用MDItem读取这些注释后不可见。我还使用MDitemCopyAttributeName列出了所有属性,kMDItemFinderComment不在其中。这种行为正确吗?swift 4是否有不同的解决方案?MDItemCreateWithURL正在为完整文件路径返回nil。