Home > Mobile >  How can I use spotlight search from swift in the same way like I do it in terminal? NSMetadataQuery?
How can I use spotlight search from swift in the same way like I do it in terminal? NSMetadataQuery?

Time:09-11

lets imagine that I need to know which apps was run in 1 week period.

Query for terminal looks like:

mdfind '(InRange(kMDItemFSContentChangeDate,$time.today(-7d),
$time.today( 1d)) && ((kMDItemContentTypeTree=com.apple.application) && 
InRange(kMDItemLastUsedDate,$time.today(-7d),$time.today( 1d))))'

so my query is:

'(InRange(kMDItemFSContentChangeDate,$time.today(-7d),
$time.today( 1d)) && ((kMDItemContentTypeTree=com.apple.application) && 
InRange(kMDItemLastUsedDate,$time.today(-7d),$time.today( 1d))))'

How can I run THIS query syntax from swift code and to receive URLs/paths as result of query?

I have seached for NSMetadataQuery but looks like I cannot use this search query as predicate in it...

Did I miss sth?

Or for query with such syntax I need to use some another instrument, but not NSMetadataQuery?

CodePudding user response:

heh, there must be used MDQuery instead of NSMetadataQuery:

//set MDQuery string
let queryString = "(InRange(kMDItemFSContentChangeDate,$time.today(-7d),$time.today( 1d)) && ((kMDItemContentTypeTree=com.apple.application) && InRange(kMDItemLastUsedDate,$time.today(-7d),$time.today( 1d))))"
let query = MDQueryCreate(kCFAllocatorDefault, queryString as CFString, nil, nil)

//run the query
MDQueryExecute(query, CFOptionFlags(kMDQuerySynchronous.rawValue))
//loop through query results
for i in 0..<MDQueryGetResultCount(query) {
    if let rawPtr = MDQueryGetResultAtIndex(query, i) {
        let item = Unmanaged<MDItem>.fromOpaque(rawPtr).takeUnretainedValue()
        //grab kMDItemPath value for each entry
        if let path = MDItemCopyAttribute(item, kMDItemPath) as? String {
        //search for certain TCC Protected Directory Paths
            print(path)
        }
    }
}

( But there is exist also async search! This is sycn version )

  • Related