I'm sending notification from the first viewController in a UITabBarController
to the second viewController in the UITabBarController
but the second viewController doesn't seem to observe or listen to for the notification until i open it....so basically i have to open the second viewController to subscribe to the Notification the go back to the first one to send it....How can i fix this such that the notification gets to the secondViewController without having to open it to subscribe
Asked
Active
Viewed 910 times
1

Sagaya Abdul
- 151
- 1
- 11
-
Try with delegates. check this https://stackoverflow.com/a/9736559/4831524 – Antony Raphel Dec 19 '17 at 11:24
-
Conceptually it would be wise to separate the model logic (where you want to receive the notifications) from the view logic (your controllers, that handle the views), since you can never be sure which controllers are currently alive. Consider ViewControllers a dynamic thing that can be created/deleted on demand. – mschmidt Dec 19 '17 at 11:32
-
To register for notification your view controller must be in memory. Otherwise how you can observe the value change ?. second thing is if both view controller in tabbar controller you can access object of second view controller form tabbar controller and add observer there like `self.tabBarController.viewControllers` – Prashant Tukadiya Dec 19 '17 at 11:35
-
If you need observer in all of your view controllers Another solution is create one Base ViewController which inherited by all your view controller. Add Observer there on view didload – Prashant Tukadiya Dec 19 '17 at 11:51
1 Answers
0
Make a notification receiving function in SecondViewController
@objc func notified(_ noti : Notification) {
print("Recieved fired noti")
}
Make a custom class of your UITabbarController
. In viewDidLoad
of your Tabbarcontroller
class write these lines
let vc = self.viewControllers![1] as! SecondViewController
NotificationCenter.default.addObserver(vc, selector: #selector(vc.notified(_:)), name: NSNotification.Name(rawValue: "NotificationSample"), object: nil)
Here I have taken the index 1 just for example, replace it with your secondViewController
index in tabbarController
.
Then post your notification from wherever you want to , just for instance, like from FirstviewController
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NotificationSample"), object: nil)
In best case scenario, this should work.

Arun Kumar
- 788
- 5
- 15