How to navigate to view controller on push notification

Patrick picture Patrick · Mar 26, 2015 · Viewed 8.4k times · Source

I'd like to navigate to a certain view controller after receiving a push notification. After navigation, the navigation stack should work as if the user got to the view manually.

The storyboard: http://www.xpos.nl/xpos/images/common/storyboard.png

In AppDelegate.swift I already have:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    println("didReceiveRemoteNotification")

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let destinationViewController = storyboard.instantiateViewControllerWithIdentifier("MessageViewController") as MessageViewController

    let navigationController = self.window?.destinationViewController;

    navigationController?.pushViewController(destinationViewController, animated: false, completion: nil)

}

But I get an error that destinationViewController is not part of window or if I correct that (trying other answers on stackoverflow), nothing happens.

Answer

Thomas picture Thomas · Mar 26, 2015

The destinationViewController is not part of the window because it has not been added, just initialized. Based on the assumption that the navigationViewController is your rootViewController, push to your destinationViewController like this:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    println("didReceiveRemoteNotification")

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let destinationViewController = storyboard.instantiateViewControllerWithIdentifier("MessageViewController") as MessageViewController

    let navigationController = self.window?.rootViewController as! UINavigationController

    navigationController?.pushViewController(destinationViewController, animated: false, completion: nil)

}

Additionally: To push from "Bestellen" to "MessageViewController" and then pop to "Berichten", you need to push all the other viewControllers between those two, too. There is no built in function or algorithm to do that.