小编典典

Swift- 来自appDelegate的pushViewController,rootViewController.navigationController为零

swift

在遵循一些指南时遇到问题,特别是 http://blog.originate.com/blog/2014/04/22/deeplinking-in-
ios/

我正在设置url方案,并且可以很好地从另一个应用程序启动该应用程序,但是传入主机或url不能正常工作。我正在为所有视图布局使用情节提要和界面生成器。

指南在appDelegate中显示此openURL:

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    if([[url host] isEqualToString:@"page"]){
        if([[url path] isEqualToString:@"/page1"]){
            [self.mainController pushViewController:[[Page1ViewController alloc] init] animated:YES];
        }
    return YES;
    }
}

这是我的版本经过简化并从其他一些来源迅速得到的信息,例如,
从AppDelegate获取ViewController的实例。在Swift中,我现在跳过url主机的条件,以消除问题中潜在的其他变量。

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
    var rootViewController = self.window!.rootViewController
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var profileViewController = mainStoryboard.instantiateViewControllerWithIdentifier("profile") as ProfileViewController

    rootViewController.navigationController.popToViewController(profileViewController, animated: true)

    return true

}

快速版本会导致崩溃: fatal error: unexpectedly found nil while unwrapping an Optional value

看来rootViewController还没有navigationController吗?


阅读 434

收藏
2020-07-07

共1个答案

小编典典

在我看来,rootViewController实际上实际上是UINavigationController类型,因此将其强制转换为声明允许我直接在其上调用pushToViewController。

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool {
    let rootViewController = self.window!.rootViewController as! UINavigationController
    let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let profileViewController = mainStoryboard.instantiateViewController(withIdentifier: "InstructionVC") as! InstructionVC
    rootViewController.pushViewController(profileViewController, animated: true)
    return true

}
2020-07-07