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

Swift如何获取iPhone/iPad所有文档并在UITableView展示文件列表

iOS获取沙盒Documents目录文件并在UITableView展示的实现步骤

注意:你当前代码获取的是当前App自身沙盒内的Documents目录,默认只能访问该App自己产生的存储在这个路径下的文件,无法直接访问整个iOS设备所有文件。如果需要访问设备公共文件、其他App的共享文件,需要额外配置权限并使用系统提供的文档选择器能力。


1. 遍历Documents目录下的所有文件/文件夹

用FileManager的contentsOfDirectory方法遍历路径下的所有条目,同时处理可能的访问错误,支持过滤隐藏文件、指定文件类型等需求。

// 定义文件数据模型,存储列表需要展示的文件信息
struct FileItem {
    let fileName: String
    let fileURL: URL
    let isDirectory: Bool
    let fileSize: Int64?
    let modifyDate: Date?
}

func fetchFilesInDocuments() -> [FileItem] {
    let docURL = getURLPathFromDocuments()
    var fileList = [FileItem]()
    let fileManager = FileManager.default
    
    do {
        // includingPropertiesForKeys 指定需要获取的文件属性,options 可配置是否跳过隐藏文件、子目录等
        let fileURLs = try fileManager.contentsOfDirectory(at: docURL, includingPropertiesForKeys: [.isDirectoryKey, .fileSizeKey, .contentModificationDateKey], options: .skipsHiddenFiles)
        
        for url in fileURLs {
            let resourceValues = try url.resourceValues(forKeys: [.isDirectoryKey, .fileSizeKey, .contentModificationDateKey])
            let isDir = resourceValues.isDirectory ?? false
            let size = resourceValues.fileSize ?? 0
            let modifyDate = resourceValues.contentModificationDate
            
            fileList.append(FileItem(
                fileName: url.lastPathComponent,
                fileURL: url,
                isDirectory: isDir,
                fileSize: size,
                modifyDate: modifyDate
            ))
        }
    } catch {
        print("读取目录失败: \(error.localizedDescription)")
    }
    return fileList
}

2. 配置UITableView数据源

在你的ViewController中声明数组存储文件列表,拿到遍历结果后刷新列表:

class FileListViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    // 列表数据源数组
    var fileList = [FileItem]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        // 读取文件后刷新列表
        fileList = fetchFilesInDocuments()
        tableView.reloadData()
    }
}

3. 实现UITableView代理和数据源方法

把文件信息渲染到Cell中:

extension FileListViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fileList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "FileCell", for: indexPath)
        let item = fileList[indexPath.row]
        cell.textLabel?.text = item.fileName
        // 区分文件夹/文件,格式化显示文件大小
        cell.detailTextLabel?.text = item.isDirectory ? "文件夹" : ByteCountFormatter.string(fromByteCount: item.fileSize ?? 0, countStyle: .file)
        return cell
    }
    
    // 可选:点击事件处理,跳转子目录或者打开文件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let item = fileList[indexPath.row]
        if item.isDirectory {
            // 跳转新的列表页,传入当前目录URL重新遍历子文件即可实现层级浏览
        } else {
            // 调用UIDocumentInteractionController预览/打开对应文件
        }
    }
}

4. 如需访问整个iOS设备的公共文件/其他App文件

需要做额外配置:

  • 在Info.plist中添加两个配置项:
    • UIFileSharingEnabled(Application supports iTunes file sharing)设为YES
    • LSSupportsOpeningDocumentsInPlace(Supports opening documents in place)设为YES
  • 若需要访问iCloud文件,还需要在Xcode的Signing & Capabilities中开启iCloud能力,勾选iCloud Documents
  • 调用系统UIDocumentPickerViewController让用户主动选择设备上的文件,获取选中文件的临时访问权限后再读取内容展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 20:51:03