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

Dan*_*uta 1 macos xcode cocoa spotlight swift

我正在 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()
Run Code Online (Sandbox Code Playgroud)

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

["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"]
Run Code Online (Sandbox Code Playgroud)

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

Jim*_*ews 5

您可以通过拉出路径属性来收集项目的 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))
    }
}
Run Code Online (Sandbox Code Playgroud)