Home > Mobile >  How to get list of all recent files from MacOs?
How to get list of all recent files from MacOs?

Time:09-11

If you will open finder and press hotkey: Shift Command F

it will open "Recents" files list.

How can I get list of URLs of all those recents files from code?

Closest that I have found is: https://developer.apple.com/documentation/appkit/nsdocumentcontroller/1514976-recentdocumenturls

but it's working with recent files of the app, but not recents files of the Finder.


Upd: as I have understood it's must be in "LSSharedFileList.h":

Shared File Lists The Shared File List API is new to Launch Services in OS X Leopard. This API provides access to several kinds of system-global and per-user persistent lists of file system objects, such as RECENT DOCUMENTS and applications, favorites, and login items. For details, see the new interface file LSSharedFileList.h information source

But I see no information about how to use it in swift.

CodePudding user response:

class Spotlight {
    static func getUrlsFrom(query: MdQuerySet) -> [URL] {
        let queryString = query.rawValue
        var result: [URL] = []
        
        let query = MDQueryCreate(kCFAllocatorDefault, queryString as CFString, nil, nil)
        
        MDQueryExecute(query, CFOptionFlags(kMDQuerySynchronous.rawValue))
        
        for i in 0..<MDQueryGetResultCount(query) {
            if let rawPtr = MDQueryGetResultAtIndex(query, i) {
                let item = Unmanaged<MDItem>.fromOpaque(rawPtr).takeUnretainedValue()
                
                if let path = MDItemCopyAttribute(item, kMDItemPath) as? String {
                    result.append(path.asURL())
                }
            }
        }
        
        return result
    }
}


enum MdQuerySet: String {
    // Do not forget to replace &amp;&amp; to &&
    
    case modifAndOpened30days = "(InRange(kMDItemFSContentChangeDate,$time.today(-30d),$time.today( 1d)) && InRange(kMDItemLastUsedDate,$time.today(-30d),$time.today( 1d)))"
}
  • Related