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

如何获取Firebase Storage中文件的元数据(含最后修改时间)

获取Firebase Storage文件元数据(Last Modified)的Swift实现

在遍历Firebase Storage文件列表的循环中,你可以通过每个StorageReference对象的getMetadata方法异步获取元数据,其中lastModifiedDate字段就是你需要的文件最后修改时间。以下是修改后的完整代码:

// Get a reference to the storage service using the default Firebase App
let storage = Storage.storage()

// Create a storage reference from our storage service
let storageRef = storage.reference()

// Create a reference to the root directory
let textRef = storageRef.child("/")

textRef.listAll { result, error in
    guard let result = result else {
        print("获取文件列表失败: \(error?.localizedDescription ?? "未知错误")")
        return
    }
    
    for item in result.items {
        // 获取当前文件的元数据
        item.getMetadata { metadata, error in
            guard let metadata = metadata else {
                print("获取\(item.name)元数据失败: \(error?.localizedDescription ?? "未知错误")")
                return
            }
            
            // 获取最后修改时间
            if let lastModified = metadata.lastModifiedDate {
                print("\(item.name) 最后修改时间: \(lastModified)")
                
                // 这里可以和本地文件的修改时间对比,判断是否需要更新
                // 示例:获取本地文件路径后对比
                // let localURL = ... // 本地文件路径
                // if let localAttributes = try? FileManager.default.attributesOfItem(atPath: localURL.path),
                //    let localModifiedDate = localAttributes[.modificationDate] as? Date {
                //    if lastModified > localModifiedDate {
                //        // 需要下载更新
                //    }
                // }
            }
        }
    }
}

关键说明

  • 每个item是StorageReference类型,直接调用getMetadata即可获取元数据,无需提前创建空的StorageMetadata对象
  • lastModifiedDate是Date?类型,可直接与本地文件的modificationDate(通过FileManager获取)对比
  • 由于getMetadata是异步操作,若需要等待所有元数据获取完成后再执行后续逻辑,可以使用DispatchGroup:
let group = DispatchGroup()

for item in result.items {
    group.enter()
    item.getMetadata { metadata, error in
        defer { group.leave() }
        // 处理元数据逻辑...
    }
}

group.notify(queue: .main) {
    print("所有文件元数据已获取完成")
}

iOS 15+ 异步/等待(Async/Await)版本

如果你的项目支持iOS 15及以上,推荐使用更简洁的async/await语法:

Task {
    do {
        let result = try await textRef.listAll()
        for item in result.items {
            let metadata = try await item.getMetadata()
            if let lastModified = metadata.lastModifiedDate {
                print("\(item.name) 最后修改时间: \(lastModified)")
                // 本地文件对比逻辑...
            }
        }
    } catch {
        print("操作失败: \(error.localizedDescription)")
    }
}

内容的提问来源于stack exchange,提问作者Nicholas Farmer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 10:02:44