我正在尝试在线程中打开文件,这是我的代码:
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)
})
当移动到主屏幕时,会显示此警告并且文件未打开
Warning: Attempt to present <_UIDocumentActivityViewController: 0x...> on <HCM.PrintVacationDecisionVC: 0x...> whose view is not in the window hierarchy!
有任何帮助解决这个问题吗?
答案 0 :(得分:6)
将下面的扩展名添加到您的应用程序中,并在任何您想要呈现任何视图控制器的地方使用它,它对我有用,希望它可以帮助您。
//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
}
}
通过以下代码呈现它:
UIApplication.topViewController()?.present(vc, animated: true, completion: nil)
答案 1 :(得分:2)
如果您尝试在viewDidLoad方法中显示模态视图控制器,可以尝试将此调用移动到viewDidAppear:方法。
答案 2 :(得分:1)
您需要找到顶视图控制器
来自
https://stackoverflow.com/a/26859650/4601900
extension UIViewController {
func topMostViewController() -> UIViewController {
// Handling Modal views
if let presentedViewController = self.presentedViewController {
return presentedViewController.topMostViewController()
}
// Handling UIViewController's added as subviews to some other views.
else {
for view in self.view.subviews
{
// Key property which most of us are unaware of / rarely use.
if let subViewController = view.nextResponder() {
if subViewController is UIViewController {
let viewController = subViewController as UIViewController
return viewController.topMostViewController()
}
}
}
return self
}
}
}
extension UITabBarController {
override func topMostViewController() -> UIViewController {
return self.selectedViewController!.topMostViewController()
}
}
extension UINavigationController {
override func topMostViewController() -> UIViewController {
return self.visibleViewController.topMostViewController()
}
}
如何使用
UIApplication.sharedApplication().keyWindow!.rootViewController!.topMostViewController()