Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Return the results of a Spotlight query synchronously from a Swift function

How can I return the results of a Spotlight query synchronously from a Swift function?

I want to return a [String] that contains the items that match the query, one item per array element.

I specifically want to find all data for Spotlight items in the /Applications folder that have a kMDItemAppStoreAdamID (if there is a better predicate than kMDItemAppStoreAdamID > 0, please let me know).

The following should be the correct query:

let query = NSMetadataQuery()
query.predicate = NSPredicate(format: "kMDItemAppStoreAdamID > 0")
query.searchScopes = ["/Applications"]

I would like to do this for code that can run on macOS 10.13+, which precludes using Swift Concurrency. My project already uses the latest PromiseKit, so I assume that the solution should use that. A bonus solution using Swift Concurrency wouldn't hurt as I will probably switch over sometime in the future, but won't be able to switch soon.

I have written code that can retrieve the Spotlight data as the [String], but I don't know how to return it synchronously from a function; whatever I tried, the query hangs, presumably because I've called various run loop functions at the wrong places.

In case it matters, the app is a macOS command-line app using Swift 5.7 & Swift Argument Parser 1.5.0. The Spotlight data will be output only as text to stdout & stderr, not to any Apple UI elements.

There isn’t a single answer to questions like these. Well, there is, and that is that on Apple platforms there’s no mechanism to perform async operations synchronously that works well in all scenarios.

You mentioned Swift Argument Parser. Does that mean you’re building a command-line tool? Because most folks with questions like this are building GUI apps, and the story with GUI apps is very different.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Return the results of a Spotlight query synchronously from a Swift function
 
 
Q