使用我的 iPad 进行测试时,UIDocumentPickerViewController 无法正常工作,但可以使用模拟器进行测试

UIDocumentPickerViewController is not working when testing with my iPad but fine with simulators

我正在创建一个应用程序来显示 select 由 UIDocumentPickerViewController 编辑 iPad 的 PDF 文件。 尽管以下代码在 Xcode 的模拟器上运行良好,但出于某种原因,它不适用于我的测试 iPad(iPad Mini,第 5 代)。我可以 select 一个文件,它的 URL 似乎是正确获取的;但是,PDF 文件未显示。

如果你能帮我弄清楚发生了什么以及如何解决这个问题,我将不胜感激。

import UIKit
import PDFKit

class ViewController: UIViewController, UIGestureRecognizerDelegate,  UIDocumentPickerDelegate {
    
    
    @IBOutlet weak var pdfView: PDFView!
    
    
    override func viewDidAppear(_ animated: Bool) {
        
        //document picker
        let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.adobe.pdf"], in: .import)
        documentPicker.delegate = self
        documentPicker.allowsMultipleSelection = false
        present(documentPicker, animated: true, completion: nil)
    }
    internal func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        print(url)
        if let pdfDocument = PDFDocument(url: url)
        {
            pdfView.autoScales = true
            pdfView.document = pdfDocument
            pdfView.displayDirection = .horizontal
            pdfView.usePageViewController(true, withViewOptions: [UIPageViewController.OptionsKey.interPageSpacing: 20])
        } else{
            print ("error, which is what I am seeing in my iPad now")
        }
    }
    
    
    
    override func viewDidLoad(){
        super.viewDidLoad()
    }

环境详情:

您忽略了 url 安全范围 这一事实。请参阅“使用外部文档”部分中的 documentation

(另请注意,在 iOS 14 中,您的 initializer 已弃用。但这是另一回事。)

对我来说,就我而言,这是一个安全问题。添加这个简单的代码解决了这个问题:

let shouldStopAccessing = pickedFolderURL.startAccessingSecurityScopedResource()
        defer {
          if shouldStopAccessing {
            pickedFolderURL.stopAccessingSecurityScopedResource()
          }
       }

我从这里得到了这段代码: