从AppDelegate中获取Swift中的ViewController实例

21

当用户点击 UILocalNotification 时,我想在 Swift 的应用委托中加载特定的 ViewController。我已经确定这是在以下函数中调用的:

func application(application: UIApplication!, didReceiveLocalNotification notification: UILocalNotification!)

但是,当我尝试访问其中一个打开的视图控制器时,我的应用程序会崩溃,我想这是因为它返回了null。这是我的尝试:

var rootViewController = self.window!.rootViewController
var storyBoard = rootViewController.storyboard
var setViewController = storyBoard.instantiateViewControllerWithIdentifier("CurrentShows") as ViewController_CurrentShows

rootViewController.navigationController.popToViewController(setViewController, animated: false)
setViewController.reloadData()

在popToViewController这一行出现了崩溃。

1个回答

27

你可以尝试:

let rootViewController = self.window!.rootViewController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("CurrentShows") as! DetailViewController
rootViewController?.navigationController?.popToViewController(setViewController, animated: false)

Swift 3:

let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let controller = mainStoryboard.instantiateViewController(withIdentifier: "viewController")
self.present(viewController, animated: true, completion: nil)

1
我尝试在函数中使用它,但它没有起作用。我正在使用xcode7和swift2。你介意更新上面的代码吗? - suisied
@suisied 可能值得在 StackOverflow 上创建一个问题,并将其链接,因为我们无法在没有看到您的代码的情况下诊断您的问题。 - fulvio
在Swift 2中无法工作...无法获取“Main”故事板。 - Async-

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接