Aya Aboud Aya Aboud - 1 year ago 64
iOS Question

Attempt to present vc whose view is not in the window hierarchy

I'm trying to open file in thread and here is my code:

DispatchQueue.main.async(execute: { () -> Void in
var documentsURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).appendPathComponent(“File.pdf")
self.docController = UIDocumentInteractionController.init(url: documentsURL as URL)
self.docController?.delegate = self as? UIDocumentInteractionControllerDelegate
self.docController?.presentPreview(animated: true)
self.docController?.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)

when move to main screen this warning is displayed and file not open

Warning: Attempt to present <_UIDocumentActivityViewController: 0x...> on <HCM.PrintVacationDecisionVC: 0x...> whose view is not in the window hierarchy!

Any help to solve this problem?

Answer Source

Add extention given bellow to your application and use it any where you want to present any view controller, it works for me hope it helps you.

//MARK: - UIApplication Extension
extension UIApplication {
    class func topViewController(viewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = viewController as? UINavigationController {
            return topViewController(viewController: nav.visibleViewController)
        if let tab = viewController as? UITabBarController {
            if let selected = tab.selectedViewController {
                return topViewController(viewController: selected)
        if let presented = viewController?.presentedViewController {
            return topViewController(viewController: presented)
        return viewController

And Present it by following code:

 UIApplication.topViewController()?.present(vc, animated: true, completion: nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download