使用Notification执行segue后ViewController deinit

时间:2015-06-09 18:40:02

标签: ios swift notifications nsnotificationcenter

我基本上收到了远程通知,我想在用户点击通知后立即将用户重定向到正确的VC。

我正在使用NSNotificationCenter从我的rootVC执行segue,将用户引导到正确的VC。

  

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

由于先前已加载观察者,因此首先调用 chooseCorrectVC 函数,因此这是我的" Init / Deinit"日志。每当调用viewDidLoad()时我都会考虑Init。

  

rootVC INIT

     

SecondVC DEINIT

     

rootVC DEINIT

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

问题是:使用 chatSegue 调用的VC无法初始化并直接进入deinit。我不知道为什么会发生这种情况,也许我没有正确删除观察者。

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

如果您收到远程通知,我建议您只需按照方法在AppDelegate.swift处理通知:

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() 
}

您可以通过此处设置标志来管理另一个视图控制器以推送homeviewcontroller的viewdidload。在视图上加载

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