ios - 使用 swift 从应用程序委托(delegate)打开 View Controller

标签 ios swift uiviewcontroller appdelegate

我正在尝试创建一个推送通知,它根据从推送中获得的信息确定打开哪个 View 。

我已经设法从推送中获取信息,但我现在正在努力让 View 打开

查看其他堆栈溢出问题,我目前有以下问题:

App Delegate 是否完成加载:

     //Extract the notification data
    if let notificationPayload = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
        // Get which page to open
        let viewload = notificationPayload["view"] as? NSString
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        //Load correct view
        if viewload == "circles" {

            var viewController = self.window?.rootViewController?.storyboard?.instantiateViewControllerWithIdentifier("Circles") as! UIViewController
            self.window?.rootViewController = viewController

                        }
    }

目前这在 var ViewController = self... 行上失败。

最佳答案

您必须如下图所示设置 ViewController StoryBoardId 属性。

enter image description here

在 swift 中使用如下代码打开 viewController

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

         let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
         let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("Circles") as UIViewController
         self.window = UIWindow(frame: UIScreen.main.bounds)
         self.window?.rootViewController = initialViewControlleripad
         self.window?.makeKeyAndVisible()

         return true
    }

适用于 iOS 13+(基于 an article by dev2qa )
打开 SceneDelegate.swift 并添加以下内容

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    // If this scene's self.window is nil then set a new UIWindow object to it.
    self.window = self.window ?? UIWindow()

    // Set this scene's window's background color.
    self.window!.backgroundColor = UIColor.red

    // Create a ViewController object and set it as the scene's window's root view controller.
    self.window!.rootViewController = ViewController()

    // Make this scene's window be visible.
    self.window!.makeKeyAndVisible()

    guard scene is UIWindowScene else { return }
}

有一个开源的navigation utility它试图使这更容易。 Example

关于ios - 使用 swift 从应用程序委托(delegate)打开 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30592521/

相关文章:

swift - Autolayout - 修改中心与乘数对齐

objective-c - dismissModalViewControllerAnimated 没有可见界面 :completion

ios - iOS 7.1.2 是否支持一维条码 - code128?

ios - 如何在自定义初始化程序中快速返回 nil?

ios - 向下滚动时如何隐藏导航栏?

ios - 为什么我的代码没有向键盘添加工具栏和完成按钮?

ios - 更改 MPMoviePlayerController 内容不适用于 performSelectorInBackground

ios - 如何快速获取委托(delegate)类的类型

ios - 如何在 iOS swift 中使用 RealmSwift 创建类似 firebase 结构的模型?

ios - 如果当前嵌套很深,如何返回根 ViewController?