如何通过代码获取macOS中Finder的最近文件URL列表?
获取Finder全局最近文件列表(Swift实现)
要获取Finder中Shift + Command + F打开的全局最近文件列表,确实需要用到Launch Services的Shared File List API(对应LSSharedFileList.h),以下是完整的Swift实现代码:
import CoreServices func getGlobalRecentDocuments() -> [URL]? { // 创建全局最近文件列表的引用 guard let recentList = LSSharedFileListCreate( nil, kLSSharedFileListRecentDocuments.takeRetainedValue(), nil ).takeRetainedValue() else { return nil } // 获取列表的当前快照(避免列表动态变化导致的问题) guard let items = LSSharedFileListCopySnapshot(recentList, nil).takeRetainedValue() as? [LSSharedFileListItem] else { return nil } var recentUrls = [URL]() for item in items { var url: Unmanaged<CFURL>? // 解析列表项对应的文件URL,禁止弹出UI提示 let status = LSSharedFileListItemResolve( item, UInt32(kLSSharedFileListItemResolveNoUI), &url, nil ) if status == noErr, let unwrappedUrl = url?.takeRetainedValue() as URL { recentUrls.append(unwrappedUrl) } } return recentUrls } // 使用示例 if let recentFiles = getGlobalRecentDocuments() { print("最近文件列表:") for url in recentFiles { print(url.path) } } else { print("无法获取最近文件列表") }
关键代码说明:
- 导入框架:
CoreServices包含了Launch Services的所有C API,必须导入才能使用LSSharedFileList相关接口。 - 创建列表引用:
kLSSharedFileListRecentDocuments是系统定义的全局最近文件列表标识符,通过LSSharedFileListCreate获取列表的核心引用。 - 快照获取:
LSSharedFileListCopySnapshot获取列表的静态快照,防止遍历过程中列表内容变化引发异常。 - 解析文件URL:
LSSharedFileListItemResolve将列表项转换为实际的文件URL,kLSSharedFileListItemResolveNoUI参数确保不会弹出权限或错误提示框。 - 内存管理:由于是基于Core Foundation的C API,需要用
takeRetainedValue()和takeUnretainedValue()管理对象的引用计数,避免内存泄漏。
这个方法获取的就是Finder中展示的全局最近文件,和NSDocumentController.recentDocumentUrls()仅返回当前App的最近文件不同,它覆盖了系统所有应用打开过的文件。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

