nspredicatensmetadataqueryicloud-drive

How do I filter NSMetadataQuery


I am trying to create a NSMetadataQuery with a predicate. At a certain point I may want to gather all videos iCloud may have at another point all images. I don't want anything else, just search for videos or search for images. Not both at the same time.

I have created this code:

CFStringRef whatToFilter = kUTTypeImage;
if (self.filterType == kKindVideo) {
    whatToFilter = kUTTypeVideo;
}

NSPredicate *predType = [NSPredicate predicateWithFormat:@"(%K == %@)", NSMetadataItemContentTypeKey, whatToFilter];

NSMetadataQuery *newQuery = [[NSMetadataQuery alloc] init];
[newQuery setSearchScopes:@[NSMetadataQueryUbiquitousDocumentsScope]];
newQuery.predicate = predType;

as soon as I add this predicate to newQuery it gives me zero results.

What is the correct syntax for this query? Don't tell me that the predicate is also not working for NSMetadataQuery, because sort is not working either.


Solution

  • The best way to create a correct NSMetadataQuery predicate is to use the Finder's query expression editor, like so:

    Smart Folder query expression editor

    Then save it as a Smart Folder and Get Info on the resulting folder:

    Smart Folder info

    The relevant Spotlight query syntax is, in this instance: "(kMDItemUserTags == 'Assets'cd)"... (Ignore the _kMDItemGroupId subexpression, as attribute names beginning with underscores are not public API.)

    Finally, let NSPredicate figure out how it wants the query string rewritten:

    let predicate = NSPredicate(fromMetadataQueryString: "(kMDItemUserTags == 'Assets'cd)")