Search code examples
iosswiftnotificationsnsnotificationcenter

ViewController deinit after performing segue using Notification


I'm basically receiving a remote notification and I want to redirect my user to the correct VC as soon as he clicks the notification.

I'm doing it using NSNotificationCenter to perform a segue from my rootVC, leading the user to the correct VC.

NSNotificationCenter.defaultCenter().addObserver(self, selector: "chooseCorrectVC:", name:chatNotificationKey, object: nil)

Since the observer was previously loaded, my chooseCorrectVC function is called first, so this is my "Init/Deinit" Log. I consider Init whenever viewDidLoad() is called.

rootVC INIT

SecondVC DEINIT

rootVC DEINIT

func chooseCorrectVC(notification:NSNotification){
    self.performSegueWithIdentifier("chatSegue", sender: notification)
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

The issue is: the VC that is called with chatSegue does not get initialized and goes straight to deinit. I'm not sure why it's happening, maybe I'm not removing the observer correctly.

Any suggestions?


Solution

  • If you are receiving the remote notification, I suggest you to just handle the notification at AppDelegate.swift at method:

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
    
    // Here you can define view controller and manage it.
       println("Received: \(userInfo)") 
    // Make root view controller first as per your need as HomeViewController in following
                    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                    var mainTabBarController = mainStoryboard.instantiateViewControllerWithIdentifier("MainTabBarController") as! MainTabBarController
                    var notificationNavController : UINavigationController = mainTabBarController.viewControllers?.first as! UINavigationController
                    var homeViewController : HomeViewController = notificationNavController.viewControllers.first as! HomeViewController
                    homeViewController.isNotified = true
                    let nav = UINavigationController(rootViewController: mainTabBarController)
                    self.window!.rootViewController = nav
                    nav.setNavigationBarHidden(true, animated: false)
                    self.window?.makeKeyAndVisible() 
    }
    

    You can manage another view controller to be push on viewdidload of homeviewcontroller via setting flag here. On view did load

    if isNotified == true {
          // Push another view controller
    }