Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for files using NSMetadataQuery does simply nothing

Tags:

swift

xcode6

I try to use NSMetadataQuery and NSPredicate to search for files. After several hours of trying and searching for solutions (I'm new to swift) I have a small example. It compiles fine but the results are zero. I tried different predicates but at the end metadataQuery.resultCount is always 0. Anyone has an idea whats going wrong?

class AppDelegate: NSObject, NSApplicationDelegate {
var metadataQuery: NSMetadataQuery!
var metadataQueryDidUpdateObserver: AnyObject?
var metadataQueryDidFinishGatheringObserver: AnyObject?


@IBOutlet weak var window: NSWindow!

func applicationDidFinishLaunching(aNotification: NSNotification) {

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "initalGatherComplete:", name: NSMetadataQueryDidFinishGatheringNotification, object: nil)

    metadataQuery = NSMetadataQuery()
    metadataQuery.searchScopes = [NSMetadataQueryIndexedLocalComputerScope]
    metadataQuery.predicate = NSPredicate(format: "%K LIKE '*'", NSMetadataItemFSNameKey)
    metadataQuery.startQuery()

}

func initalGatherComplete(notification: NSNotification) {
    metadataQuery.stopQuery()

    let resultCounter = metadataQuery.resultCount
    NSLog("%lu", resultCounter)

    NSNotificationCenter.defaultCenter().removeObserver(self, name: NSMetadataQueryDidFinishGatheringNotification, object: nil)
}

And last but not least: the current predicate should list all files, but at the end the predicate should only list applications. whats the best practice to create such a predicate? I planned to filter for the extension .app but perhaps there is a better way?

Thanks!

like image 648
gkoeder Avatar asked Feb 01 '15 13:02

gkoeder


1 Answers

Check your predicate syntax. The LIKE operator isn't available for NSMetadataQuery predicate searches (in fact NSPredicate uses a quite similar but actually different set of operators and behavior in the context of Spotlight metadata searches.)

NSMetadataQuery's syntax for glob searches just uses an equals sign:

NSPredicate(format: "%K ==[cd] '*'", NSMetadataItemFSNameKey)
like image 158
iluvcapra Avatar answered Sep 18 '22 02:09

iluvcapra