【问题标题】:How to present a view controller from appdelegate xcode 11 swift 5如何从 appdelegate xcode 11 swift 5 呈现视图控制器
【发布时间】:2020-04-05 22:03:38
【问题描述】:

我整天都在寻找如何在 appdelegate 中呈现视图控制器。看来,在 xcode 11 中,window 属性已移至让我感到困惑的场景代理。我想从 didReceiveRemoteNotification 函数的 appdelegate 中呈现一个视图控制器,这样当用户收到通知时,它会将他们带到带有信息的单独视图控制器。我已经尝试过:

self.window?.rootViewController?.present(LoginViewController(), animated: false, completion: nil)

在我以前的应用程序中曾经工作过的 appdelegate 中,但它似乎不再工作了。任何帮助将不胜感激。

【问题讨论】:

  • 困难的部分是呈现视图控制器,还是接收远程通知?
  • 您可以从UIApplication 对象中获取connectedScenes。您需要选择一个来显示新的视图控制器。
  • 困难的部分是呈现视图控制器。我能够收到通知。

标签: ios swift xcode


【解决方案1】:

我能够通过使用共享窗口从 scenedelegate 获取窗口以呈现视图控制器来解决此问题。

UIApplication.shared.windows.first?.rootViewController?.present(vc, animated: false, completion: nil)

【讨论】:

    【解决方案2】:

    通过应用程序委托呈现视图控制器的最佳方法是不落入如下层次结构:

    if let vc = UIStoryboard(name: "YOURSTORYBOARD", bundle: nil).instantiateViewController(withIdentifier: "YOURVIEWCONTROLLER") as? YOURVIEWCONTROLLER {
    if let window = self.window, let rootViewController = window.rootViewController {
        var currentController = rootViewController
        while let presentController = currentController.presentedViewController {
            currentController = presentController
        }
           currentController.present(vc, animated: true, completion: nil)
       }
    } 
    

    【讨论】:

    • 我没有使用故事板。
    • @KushalShrestha 我很高兴,它帮助了你。
    猜你喜欢
    • 2015-02-27
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多