1

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)
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Alexander George
  • 871
  • 9
  • 22
  • Why are you creating a new instance of `MyViewController` just to show the document picker? Shouldn't you be calling `importFromFiles` on an existing and visible instance of a view controller? – rmaddy May 03 '19 at 01:32

1 Answers1

1

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)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87