Vege
Vege

Reputation: 11

Detect UIViewController change from AppDelegate

I'm trying to execute a function every time the app loads a new ViewController (transitioning to a different view). To avoid calling this function inside each ViewController (there are about 10 of them and more to be added), I'm hoping to do this in the AppDelegate by adding some sort of observer. Is this possible? Or can it somehow be done with the help of UIViewController extension?

Upvotes: 0

Views: 1388

Answers (2)

lubilis
lubilis

Reputation: 4170

Forget AppDelegate, observers or extensions, use Inheritance.

All your UIViewControllers should extend a MainViewController base class and you can put your logic in viewDidLoad method (or viewDidAppear) of base class.

Remember to call super class method when override.

Upvotes: 1

Ostap Horbach
Ostap Horbach

Reputation: 338

Alternatively you can subclass UINavigationController and post notifications on events you are interested in:

class NotificationNavigationController: UINavigationController {
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        NotificationCenter.default.post(name: Notification.Name(rawValue: "NavigationControllerWillPush"), object: nil)
        super.pushViewController(viewController, animated: animated)
    }

    override func popViewController(animated: Bool) -> UIViewController? {
        NotificationCenter.default.post(name: Notification.Name(rawValue: "NavigationControllerWillPop"), object: nil)
        return super.popViewController(animated: animated)
    }
}

Then in your Application Delegate you can observe those notifications:

NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "NavigationControllerWillPush"), object: nil, queue: OperationQueue.main) {
            notification in
            // handle push
        }
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "NavigationControllerWillPop"), object: nil, queue: OperationQueue.main) {
            notification in
            // handle pop
        }

Upvotes: 1

Related Questions