Search code examples
iosswiftnsnotificationcenternotificationcenter

NotificationCenter: How to add a notification in BaseController without it being added multiple times?


I have a BaseViewController and all the view controllers in my app inherits from this BaseViewController class. I want to listen to a custom notification in some of my view controllers. I added the following code in viewWillAppear and viewWillDisappear methods of BaseViewController

    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(self.actOnNotification), name: NSNotification.Name("MyNotification"), object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(NSNotification.Name("MyNotification"))
    }

My app is designed in such a way that the main page gets loaded after a custom splash view controller and an another view controller (both of these inherit from BaseViewController too). Basically, it is the third view controller in the stack.

Now, the actOnNotification method gets called three times when the home page of my app loads. Is there a way that I can have it called only for once, when the home page loads?

It obviously works if I listen to notification directly in home page of the app.


Solution

  • You can used a navigationController for mainViewController after that you implement addObserver in navigationController

    class MainNavigationViewController: UINavigationController {
    
          override func viewWillAppear(_ animated: Bool) {
            NotificationCenter.default.addObserver(self, selector: #selector(self.actOnNotification), name: NSNotification.Name("MyNotification"), object: nil)
        }
        
        override func viewWillDisappear(_ animated: Bool) {
            NotificationCenter.default.removeObserver(NSNotification.Name("MyNotification"))
        }
    }
    

    Also you can get currentViewcontroller

        guard let currentViewcontroller = self.viewControllers.last() else { return}