如何获取NSMetadataItem的URL - macOS Cocoa Swift 3

时间:2016-11-11 19:18:54

标签: swift xcode macos cocoa spotlight

我正在Mac OS上编写第一个应用程序,我想在我的mac上找到所有XCode文件(项目)。所以我写了一些代码:

NotificationCenter.default.addObserver(self, selector: #selector(initalGatherComplete(notification:)), name:   NSNotification.Name.NSMetadataQueryDidFinishGathering , object: nil)

metadataQuery.searchScopes = [NSMetadataQueryLocalComputerScope]
metadataQuery.predicate = NSPredicate(format: "kMDItemFSName contains %@ OR kMDItemFSName contains %@", argumentArray: [".xcworkspace", ".xcodeproj"])

metadataQuery.operationQueue = OperationQueue.main
metadataQuery.start()

它正常工作。我收到商品属性键:

["kMDItemContentTypeTree", "kMDItemContentType", "_kMDItemOwnerUserID", "kMDItemPhysicalSize", "kMDItemKind", "kMDItemDateAdded", "kMDItemContentCreationDate", "kMDItemContentModificationDate", "kMDItemLogicalSize", "kMDItemDisplayName", "kMDItemUsedDates", "kMDItemLastUsedDate", "kMDItemUseCount", "kMDItemFSName", "kMDItemFSSize", "kMDItemFSCreationDate", "kMDItemFSContentChangeDate", "kMDItemFSOwnerUserID", "kMDItemFSOwnerGroupID", "kMDItemFSNodeCount", "kMDItemFSInvisible", "kMDItemFSTypeCode", "kMDItemFSCreatorCode", "kMDItemFSFinderFlags", "kMDItemFSHasCustomIcon", "kMDItemFSIsExtensionHidden", "kMDItemFSIsStationery", "kMDItemFSLabel"]

现在,问题是如何获取我收到的项目的URL?在属性中,我找不到任何文件在光盘上的位置。

1 个答案:

答案 0 :(得分:4)

您可以通过拉出路径属性来收集项目的URL:

var urls = [URL]()
for result in metadataQuery.results {
    if let item = result as? NSMetadataItem,
        let path = item.value(forAttribute: NSMetadataItemPathKey) as? String {
        urls.append(URL(fileURLWithPath: path))
    }
}