madelman
madelman

Reputation: 317

Correct way to show ViewController from push notification when app is closed

I'm trying to show a view controller when my app is open from a push notification, but it's crashing because I'm trying to get the UINavigationController, which is not still initialized in the AppDelegate didFinishLaunchingWithOptions function.

My code is this:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    if let userInfo = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let profileController = storyboard.instantiateViewControllerWithIdentifier("profileViewControllerIdentifier") as! ProfileViewController

        let navigationController = self.window?.rootViewController as! UINavigationController
        navigationController.pushViewController(profileController, animated: false)
    }
}

What is the correct way to show a ViewController when coming from a push notification when the app was closed?

Upvotes: 2

Views: 752

Answers (2)

madelman
madelman

Reputation: 317

Just found what the problem was, I was accessing some data from the navigationcontroller, which was not still initialized.

Upvotes: 0

Gabriel Goncalves
Gabriel Goncalves

Reputation: 5160

So, the main reason I see is that your rootViewController is not a UINavigationController. It could be because:

  1. rootViewController is another UIViewController
  2. The UINavigationController is not set as the rootViewController in your storyboard.

So without any print about what are you getting from self.window?.rootViewController I think you can run this line to see if you can get your UINavigationController:

var myNav = storyboard.instantiateViewControllerWithIdentifier("myNavIdHere") as? UINavigationController

just make sure to add an ID to your UINavigationController. (this is just to check you can reach your NavController)

Upvotes: 0

Related Questions