Search code examples
swiftxcodemacoscocoaspotlight

How to get URL of NSMetadataItem - macOS Cocoa Swift 3


I'm writing first app on mac OS and I would like to find all XCode files (project) on my mac. So I wrote some code:

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()

and it's work correctly. I receive item attributes keys:

["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"]

Now, the question is how to get URL of item which I receive? In attributes I can't find anything, where the file is on disc.


Solution

  • You can gather the URLs for the projects by pulling out the path attribute:

    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))
        }
    }