3

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?

Blasmo
  • 458
  • 3
  • 18

1 Answers1

2

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])
dldnh
  • 8,923
  • 3
  • 40
  • 52
  • Thank you for the help. Now I do get a result back, but it's always an empty array, even when I stocked the folder with soms .txt files. – Blasmo Mar 10 '21 at 15:23
  • I have tried different nspredicates, but I keep getting an empty array back so maybe there is still another problem left. – Blasmo Mar 10 '21 at 15:31
  • 2
    Here's the file I was playing with, in case it might help in isolation: https://gist.github.com/dldnh/819f11633359222bcf361a8da6e38a06 – dldnh Mar 10 '21 at 19:12
  • 1
    Your app uses a separate set of directories when it is sandboxed. In case you're looking to access the user's `~/Documents` directory instead, make sure to follow this answer: https://stackoverflow.com/a/59752583 – glocore Jul 27 '21 at 17:08