UIDocumentInteractionController:不能 use/save 个文件

UIDocumentInteractionController: cannot use/save files

在我的应用程序中,我显示了一些远程图像或 PDF 文件,并想让用户能够下载它们。为此,我尝试先将它们保存在 .documentDirectory 中,然后再打开 UIDocumentInteractionController 来处理文件。

但是,我遇到了一个问题,即即使操作 sheet 正常打开并提出所有预期的选项,最后我也永远无法使用该文件,因为出现错误。具体来说:

这是我用来缓存远程文件的代码,然后用 UIDocumentInteractionController:

打开它
URLSession.shared.downloadTask(with: url) { localUrl, response, error in
    if let localUrl = localUrl {
        do {
            let imageData = try Data(contentsOf: localUrl)
            let d = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
            if let docUrl = d?.appendingPathComponent(url.lastPathComponent) {
                try imageData.write(to: docUrl)
                self.download(docUrl)
            }
        } catch {
            print("Oops: \(error)")
        }
    }
}.resume()

func download(_ url: URL) {
    DispatchQueue.main.async {
        let documentInteractionController = UIDocumentInteractionController()
        documentInteractionController.delegate = self
        documentInteractionController.url = url
        documentInteractionController.uti = url.typeIdentifier ?? "public.data, public.content"
        documentInteractionController.name = url.localizedName ?? url.lastPathComponent
        documentInteractionController.presentOptionsMenu(from: self.view.frame, in: self.view, animated: true)
    }
}

感谢您的帮助

我不能告诉你为什么它不适用于 UIDocumentInteractionController,但它确实适用于 UIActivityViewController。

    private func download(_ url: URL)
    {
        DispatchQueue.main.async {
            let avc = UIActivityViewController(activityItems: [url], applicationActivities: nil)
            self.present(avc, animated: true, completion: nil)
        }
    }