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

iOS应用如何访问文件与文件夹标签?是否有可用API?

好问题!iOS确实给开发者提供了访问文件标签(就是你在Files应用和Mac Finder里看到的那些彩色标签)的API——核心是通过FileManager(Swift)/NSFileManager(Objective-C)结合URLResourceKey相关接口实现。下面给你一步步拆解具体操作:

一、获取Documents目录下的所有标签列表

要拿到Documents里所有文件/文件夹的标签并去重,可以遍历目录里的每个条目,提取标签后存入集合自动去重:

func getAllUniqueTagsInDocuments() throws -> [String] {
    guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
        throw NSError(domain: "TagAccessError", code: 1, userInfo: [NSLocalizedDescriptionKey: "无法获取Documents目录"])
    }
    
    // 遍历目录,只读取标签属性
    let enumerator = FileManager.default.enumerator(at: documentsURL, 
                                                    includingPropertiesForKeys: [.tagNamesKey], 
                                                    options: [.skipsHiddenFiles])
    
    var allTags = Set<String>()
    while let fileURL = enumerator?.nextObject() as? URL {
        let resourceValues = try fileURL.resourceValues(forKeys: [.tagNamesKey])
        if let tags = resourceValues.tagNames {
            allTags.formUnion(tags)
        }
    }
    
    return Array(allTags)
}
二、读取单个文件/文件夹的标签

通过resourceValues(forKeys:)方法直接获取目标URL的标签属性:

func getTags(for fileURL: URL) throws -> [String]? {
    let resourceValues = try fileURL.resourceValues(forKeys: [.tagNamesKey])
    return resourceValues.tagNames
}
三、设置文件/文件夹的标签

利用setResourceValues(_:)方法修改目标URL的标签数组,支持同时设置多个标签:

func setTags(_ tags: [String], for fileURL: URL) throws {
    var resourceValues = URLResourceValues()
    resourceValues.tagNames = tags
    try fileURL.setResourceValues(resourceValues)
}
四、关键注意事项
  • 标签在iOS和macOS间通过iCloud同步,API行为跨平台一致,你设置的标签会同步到Files应用和Finder里
  • 确保应用有对应文件的访问权限:如果是Documents目录内的自有文件,默认有权限;如果是外部文件,需要通过UIDocumentPickerViewController获取访问权限
  • 标签是字符串数组,支持空数组(清除所有标签),和Files应用的操作逻辑完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:21:59