在哪里可以找到用 URL 下载的文件?

Where to find the file downloaded with a URL?

当我使用 URL:

下载文件时
guard let url = url else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
    guard let data = data, error == nil else {
        return
    }
    if let doc = PDFDocument(data: data) {
        DispatchQueue.main.async {
            self.document = doc
        }
    }
}
task.resume()

文件是保存在目录中还是我必须保存它?如果是前者,文件保存在哪里?我尝试使用文件名查找文件,但无处可寻:

guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileName = url.lastPathComponent
let localURL = documentsDirectory.appendingPathComponent(fileName)

URLSession docs 中提到:

Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests to a server.

Download tasks retrieve data in the form of a file, and support background downloads and uploads while the app isn’t running.

由于您使用的是 URLSession.shared.dataTask(with:),它为您提供了数据的内存表示形式。如果你想把它保存到一个文件中,你不妨使用downloadTask,然后在下载完成后将文件移动到适当的目录。

您没有下载文件。您正在将 URL 中的内容下载到数据对象中,然后将该数据转换为 PDFDocument,这是 PDF 文档的内存表示形式。

如果要将文件保存到磁盘,则需要将文件保存到磁盘。您当前的代码不会这样做。

PDFDocument class 包括方法 write(to:),它将您的 PDF 文档保存到磁盘。您必须构建一个 URL 来描述磁盘上文件的路径,然后使用 write(to:) 保存到 URL.