MacOS系统中如何获取文件的Last opened属性?
获取macOS文件的“Last opened”日期
在macOS系统中,部分文件带有「Last opened」(最后打开时间)属性,目前你已经可以通过FileManager获取文件的修改日期和创建日期:
// 修改日期 try? FileManager.default.attributesOfItem(atPath: url.path)[FileAttributeKey.modificationDate] as? Date // 创建日期 try? FileManager.default.attributesOfItem(atPath: url.path)[FileAttributeKey.creationDate] as? Date
要获取「Last opened」日期,有两种常用方法:
方法一:直接通过FileManager读取系统属性
macOS的FileAttributeKey提供了lastOpenDate键,可直接读取该属性,代码示例:
// 获取最后打开时间 do { let attributes = try FileManager.default.attributesOfItem(atPath: url.path) if let lastOpenDate = attributes[FileAttributeKey.lastOpenDate] as? Date { // 成功获取到最后打开时间 print("最后打开时间:\(lastOpenDate)") } else { // 文件无该属性记录 print("未找到最后打开时间记录") } } catch { print("读取文件属性失败:\(error)") }
注意:这个属性仅在系统记录过文件打开行为时存在,从未打开过的文件或部分系统文件可能没有该值。
方法二:通过Spotlight查询
Spotlight会索引文件的使用记录,通过CoreSpotlight框架可以更稳定地获取最后打开时间,代码示例:
import CoreSpotlight // 构建查询,匹配目标文件路径 let query = CSSearchableItemQuery(queryString: "kMDItemPath == '\(url.path)'") // 指定要获取的属性:最后使用时间 query.fetchAttributes = [kMDItemLastUsedDate as String] // 执行查询 query.start { items, error in guard let items = items, error == nil else { print("查询失败:\(error?.localizedDescription ?? "未知错误")") return } if let item = items.first, let lastUsedDate = item.attributes[kMDItemLastUsedDate as String] as? Date { print("最后打开时间:\(lastUsedDate)") } else { print("未找到最后打开时间记录") } }
注意:使用该方法需要确保应用拥有对应文件的访问权限,访问隐私目录(如Documents、Downloads)时需在Info.plist中配置权限描述。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

