【发布时间】:2015-01-15 15:00:54
【问题描述】:
我创建了一个使用故事板的应用程序,并成功创建了一个可以正常工作的表格视图和详细信息页面。
我希望这样可以将滑动 localNotifications 的用户发送到应用内正确的详细信息页面。
看来我可以从 ViewController 调用函数,但是每当它们引用自己来更新任何细节或执行 segue 时,应用程序就会崩溃。
我的 ViewController 中的代码如下:
func handleMessageNotification (messageID:String)
{
// this function should act as a conduit for the call from the delegate
println("notif messageID: \(messageID)");
self.performSegueWithIdentifier("showMessageDetail", sender: self);
self.messageView.reloadData();
}
这是从我的 appDelegate 调用的
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
if (application.applicationState == UIApplicationState.Background || application.applicationState == UIApplicationState.Inactive)
{
var rootViewController = self.window!.rootViewController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ViewController") as ViewController
rootViewController?.navigationController?.popToViewController(setViewController, animated: false)
setViewController.handleMessageNotification(messageID);
}
}
println 工作正常,但 performSegue 失败(致命错误:在展开 Optional 值时意外发现 nil)并且 messageView.reload() 失败(同样的错误)。
如何在打开应用程序时收到通知以将应用程序触发到正确的位置?
这个解决方案“Get Instance Of ViewController From AppDelegate In Swift”使用了很多相同的方法,但我的解决方案不允许使用 ViewController 访问任何内容。
======= 更新 - 解决方案 =======
对于其他有此问题的人。继Gabuh在下面提出的建议之后;我的完整解决方案是执行以下操作:
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
if (application.applicationState == UIApplicationState.Background || application.applicationState == UIApplicationState.Inactive)
{
let navigationController = application.windows[0].rootViewController as UINavigationController;
navigationController.popToRootViewControllerAnimated(false); // I need to push back to root before performing segue
let rootViewController = navigationController.visibleViewController;
rootViewController.performSegueWithIdentifier("showMessageDetail", sender: self);
}
}
这也允许我调用视图中的函数,例如原始示例中的函数,例如
rootViewController.handleMessageNotificaion(messageID);
或
rootViewController.messageView.reloadData();
【问题讨论】:
-
我得到:对于以“let navigationController”开头的行,无法将“myApp.ViewControllerMain”(0x37b18)类型的值转换为“UINavigationController”
-
我对此不太满意,但这可能表明您的根视图不是导航项?上面的代码假定导航器是根视图。您可能需要添加一个断点以查看您的导航在堆栈中的位置并相应地更改引用。