首页 > 解决方案 > 从 UIDocumentPicker 获取的本地 URL 在 2 或 3 分钟后不起作用

问题描述

我有两个问题,在谷歌搜索 5 天后无法找到答案。

  1. 在我的帮助下,uidocumentpicker我曾经访问过文件并选择了一个 pdf 文档。借助didpicdocuments方法选择 pdf 后,我得到了 pdf 的 URL 并将其存储到一个数组中。并在表格视图中以该pdf的名称显示一行。现在,当用户单击 pdf 正在打开的那一行pdfkit以及存储在该数组中的 URL 时。到目前为止,一切正常。现在问题出在两三分钟后,当我再次点击该行时,它没有打开那个 pdf,它只打开一个空白pdfview

  2. 在打开选择 pdf 时,我只想选择 pdf 文件,而不是其他文件,为此,我使用了移动核心服务,并在文档选择器的文档类型中提到了 pdf 类型。但即使在它之后我也无法选择pdf文件,它也不起作用。

谢谢

func didSelectDocument(doc: String?) {
    let importMenu = UIDocumentPickerViewController(documentTypes: [String("kUTTypePDF")], in: .import)
    importMenu.delegate = self
    //importMenu.allowsMultipleSelection = true
    importMenu.modalPresentationStyle = .formSheet
    self.present(importMenu, animated: true, completion: nil)
}

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    if let url = urls.first {
        urlArray.append(url)
    }
}

用于打开 pdf

let vc = UIViewController()
        vc.view.backgroundColor = .white
        let pdfView = PDFView(frame: CGRect(x: 0, y: 0, width: vc.view.frame.width, height: vc.view.frame.height))
        let pdfDocument2 = pdfDocuments[indexPath.row-(imageSelected.count)]
        pdfView.displayMode = .singlePageContinuous
        pdfView.autoScales = true

        pdfView.document = pdfDocument2.pdf
        vc.view.addSubview(pdfView)

        navigationController?.pushViewController(vc, animated: true)

标签: iosswiftxcode

解决方案


你无法保存它们。URL 是沙箱中的一个临时漏洞。从文档UIDocumentPickerViewController

不要保存打开和移动操作提供的 URL。但是,您可以将书签保存到这些 URL。调用 bookmarkData(options:includingResourceValuesForKeys:relativeTo:) 方法并传入 withSecurityScope 选项,创建一个包含安全范围 URL 的书签。

您需要保存一个安全范围书签,它本质上是一个 blobData


推荐阅读