Search code examples
swiftmacosappkit

Appkit: How to perform an NSMetadataQuery on a Local Folder


I'm trying to perform an NSMetadataQuery on a local macOS Folder (not in iCloud) using Appkit like this:

    let query = NSMetadataQuery()
    query.valueListAttributes = [ NSMetadataItemURLKey ]
    //Set the App's Documents folder as the SearchScope
    query.searchScopes = [FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!]
    NotificationCenter.default.addObserver(self, selector: #selector(handleQueryNotification), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: query)
    query.enableUpdates()
    query.start()

However, I never get a notification that the query finished gathering results. When I change the searchScope to [NSMetadataQueryUbiquitousDocumentsScope], I do get a notification.

From Apple's documentation it seems that this should be possible:

This array can contain NSURL or NSString objects that represent file-system directories or the search scopes for the query

Is there something I'm doing wrong?


Solution

  • You didn't indicate what you're looking for, but before calling query.start, you first have to set query.predicate

    (per doc: https://developer.apple.com/documentation/foundation/nsmetadataquery)

    for example:

            query.predicate = NSPredicate(format: "%K LIKE '*.txt'", argumentArray: [NSMetadataItemFSNameKey])