如何检索所有可用的Finder标签?

时间:2017-01-21 13:30:10

标签: swift macos cocoa finder

我试图检索所有可用Finder标签的列表。

我发现NSWorkspace().fileLabels确实返回了一个数组,但只返回了一个标记颜色数组,而不是标记本身:

print(NSWorkspace.shared().fileLabels) // prints ["None", "Gray", "Green", "Purple", "Blue", "Yellow", "Red", "Orange"]

您可以看到甚至不是所有默认代码,它都缺少主页工作重要,以及显然没有我创建的任何自定义的。看起来它只是与fileLabelColors一起使用的好名字。

我找到了NSMetadataQuery来实际搜索内容,但是如何获取我在Finder中创建的所有标签的列表?

1 个答案:

答案 0 :(得分:1)

NSWorkspace.shared().fileLabels仅返回创建用户帐户时可用的系统标记(默认系统标记)。

很遗憾,macOS中没有API来检索您在Finder中自己创建的标记。

解决方案是解析~/Library/SyncedPreferences/com.apple.finder.plist

func allTagLabels() -> [String] {
    // this doesn't work if the app is Sandboxed:
    // the users would have to point to the file themselves with NSOpenPanel
    let url = URL(fileURLWithPath: "\(NSHomeDirectory())/Library/SyncedPreferences/com.apple.finder.plist")
    let keyPath = "values.FinderTagDict.value.FinderTags"
    if let d = try? Data(contentsOf: url) {
        if let plist = try? PropertyListSerialization.propertyList(from: d, options: [], format: nil),
            let pdict = plist as? NSDictionary,
            let ftags = pdict.value(forKeyPath: keyPath) as? [[AnyHashable: Any]]
        {
            return ftags.flatMap { $0["n"] as? String }
        }
    }
    return []
}

let all = allTagLabels()
print(all)

这将获得所有 Finder标签标签。

您也可以只选择自定义标签(忽略系统标签):

func customTagLabels() -> [String] {
    let url = URL(fileURLWithPath: "\(NSHomeDirectory())/Library/SyncedPreferences/com.apple.finder.plist")
    let keyPath = "values.FinderTagDict.value.FinderTags"
    if let d = try? Data(contentsOf: url) {
        if let plist = try? PropertyListSerialization.propertyList(from: d, options: [], format: nil),
            let pdict = plist as? NSDictionary,
            let ftags = pdict.value(forKeyPath: keyPath) as? [[AnyHashable: Any]]
        {
            return ftags.flatMap { tag in
                if let n = tag["n"] as? String,
                    tag.values.count != 2
                {
                    return n
                }
                return nil
            }
        }
    }
    return []
}