简体   繁体   中英

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

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?

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)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM