在 macOS Big Sur 上列出目录中的所有文件

Listing all files in a directory on macOS Big Sur

中,我询问了如何将文件保存在用户选择的目录中。回复是下面的代码,效果很好

func resolveURL(for key: String) throws -> URL {
    if let data = UserDefaults.standard.data(forKey: key) {
        var isStale = false
        let url = try URL(resolvingBookmarkData: data, options:[.withSecurityScope], bookmarkDataIsStale: &isStale)
        if isStale {
            let newData = try url.bookmarkData(options: [.withSecurityScope])
            UserDefaults.standard.set(newData, forKey: key)
        }
        return url
    } else {
        let panel = NSOpenPanel()
        panel.allowsMultipleSelection = false
        panel.canChooseDirectories = true
        panel.canCreateDirectories = true
        panel.canChooseFiles = false
        if panel.runModal() == .OK,
           let url = panel.url {
            let newData = try url.bookmarkData(options: [.withSecurityScope])
            UserDefaults.standard.set(newData, forKey: key)
            return url
        } else {
            throw ResolveError.cancelled
        }
    }
}

func saveFile(filename: String, contents: String) {
    do {
        let directoryURL = try resolveURL(for: "savedDirectory")
        let documentURL = directoryURL.appendingPathComponent (filename + ".txt")
        print("saving " + documentURL.absoluteString)
        try directoryURL.accessSecurityScopedResource(at: documentURL) { url in
            try contents.write (to: url, atomically: false, encoding: .utf8)
        }
        
    } catch let error as ResolveError {
        print("Resolve error:", error)
    } catch {
        print(error)
    }
}

现在,下一步是转到用户在应用加载时选择的目录,如果有任何文件,请准备好每个文件并将这些文件的内容添加到我用来保存数据的结构中.

谷歌搜索了一下,我发现你可以使用 FileManager.default.contentsOfDirectory 读取目录中的所有文件,所以我写道:

func loadFiles() {
    do {
        let directoryURL = try resolveURL(for: "savedDirectory")
        let contents = try FileManager.default.contentsOfDirectory(at: directoryURL,
                                                        includingPropertiesForKeys: nil,
                                                        options: [.skipsHiddenFiles])
        
        for file in contents {
            print(file.absoluteString)
        }
        
    } catch let error as ResolveError {
        print("Resolve error:", error)
        return
    } catch {
        print(error)
        return
    }
}

但是,我收到以下错误:

Error Domain=NSCocoaErrorDomain Code=257 "The file “myFiles” couldn’t be opened because you don’t have permission to view it." UserInfo={NSURL=file:///Users/aleph/myFiles, NSFilePath=/Users/aleph/myFiles, NSUnderlyingError=0x600000704ba0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

看我的代码我猜这是因为我没有使用 directoryURL.accessSecurityScopedResource。我试图添加它,或找到任何其他方式,但我 运行 进入了一个块,我不知道如何到达保存在 savedDirectory 中的目录并遍历每个文件,阅读其内容。

感谢您的帮助

如果我使用:

directoryURL.startAccessingSecurityScopedResource()
// load the files
directoryURL.stopAccessingSecurityScopedResource()

然后就可以了。