Search code examples
iosswiftdelegatesuidocumentpickerviewcontroller

documentPicker delegate not called by UIDocumentPickerViewController


I have the following ViewController that implements functionality for importing files into the app using the 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)
    
  }
  
}

As you can see, the importFromFiles method receives a ViewController, which is simply the active VC. This method is called from the AppDelegate.

For now, the documentPicker method looks just as follows:

extension MyViewController: UIDocumentPickerDelegate {

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

}

The picker is displayed and dismissed correctly, but the delegate is never called and therefore the print never executed.

Edit 1

The call to the importFromFiles method is happening inside the AppDelegate. More specifically, it happens while defining a closure for a SwiftTweaks tweak:

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

Solution

  • It appears you need to retain the main object as you have

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

    inside where you present that picker here MyViewController() isn't retained so make it an instance var like

    var main = MyViewController()
    

    main.importFromFiles(origin:self)