I try to list all of my file on my Mac for an app that I made. I use NSMetadataQuery but it's not working.
Here is the code:
import Cocoa
class ViewController: NSViewController
{
let metadataQuery = NSMetadataQuery()
@IBOutlet weak var searchTextField: NSTextField!
@IBOutlet weak var labelML: NSTextField!
@IBAction func searchClick(sender: AnyObject)
{
labelML.stringValue = "Hello \(searchTextField.stringValue)!"
startQuery()
handleMetadataQueryFinished(metadataQuery)
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func startQuery()
{
print("Starting the query now...")
metadataQuery.searchScopes = [NSMetadataQueryUbiquitousDataScope]
let predicate = NSPredicate(format: "%K ==[cd] '*'", NSMetadataItemFSNameKey)
metadataQuery.predicate = predicate
if metadataQuery.startQuery(){
print("Successfully started the query.")
} else {
print("Failed to start the query.")
}
}
func handleMetadataQueryFinished(sender: NSMetadataQuery)
{
print("Search finished");
metadataQuery.disableUpdates()
metadataQuery.stopQuery()
print("Number of results \(metadataQuery.resultCount)")
for item in metadataQuery.results as! [NSMetadataItem]
{
let itemName = item.valueForAttribute(NSMetadataItemFSNameKey)
as! String
let itemUrl = item.valueForAttribute(NSMetadataItemURLKey)
as! NSURL
let itemSize = item.valueForAttribute(NSMetadataItemFSSizeKey)
as! Int
print("Item name = \(itemName)")
print("Item url = \(itemUrl)")
print("Item size = \(itemSize)")
}
}
}
As you can see, I print the number of results of the metaQuery and it answers 0.
I've try to change some things like NSMetadataQueryIndexedLocalComputerScope instead of NSMetadataQueryUbiquitousDataScope or the format of the predicate but either way it's not working.
Any idea why?
You should register an observer for
NSMetadataQueryDidFinishGatheringNotificationand wait till its called. The search takes a little while. And did starting the query returntrue?Here is some Objective-C style example from my code: