You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:25:16