UIDocumentPickerViewController 未调用 documentPicker 委托

documentPicker delegate not called by UIDocumentPickerViewController

我有以下 ViewController 实现了使用 UIDocumentPickerViewController 将文件导入应用程序的功能:

class MyViewController: UIViewController {
 
  override func viewDidLoad() {
    super.viewDidLoad()
  }
  
  func importFromFiles(origin: UIViewController?) {
         
    let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeContent as String], in: .import)
    documentPicker.delegate = self
    documentPicker.allowsMultipleSelection = true
      
    origin?.present(documentPicker, animated: true, completion: nil)
    
  }
  
}

如您所见,importFromFiles 方法接收一个 ViewController,这只是活动的 VC。此方法是从 AppDelegate.

调用的

目前,documentPicker 方法如下所示:

extension MyViewController: UIDocumentPickerDelegate {

  func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    print("Files picked")
  }

}

选择器正确显示和关闭,但从未调用委托,因此 print 从未执行。

编辑 1

importFromFiles 方法的调用发生在 AppDelegate 内部。更具体地说,它发生在为 SwiftTweaks 调整定义闭包时:

MyTweaks.importFromFiles.addClosure {
  let topViewController = visibleViewController(root: self.window?.rootViewController)
  let myVC: MyViewController = MyViewController()
  myVC.importFromFiles(origin: topViewController)
}

看来您需要保留现有的主要对象

let myVC: MyViewController = MyViewController()
myVC.importFromFiles(origin: topViewController)

在你在这里显示选择器的地方 MyViewController() 没有被保留,所以让它成为一个像

这样的实例变量
var main = MyViewController()

main.importFromFiles(origin:self)