Trigger an event / method when UIWindow RootViewCo

2019-07-20 13:39发布

问题:

I'm working on an iOS framework. I have a requirement to log events when user enters or exits a particular View Controller. For that I was thinking if somehow I could be able to register a notification to trigger a custom method when the root view controller changes. Or perhaps use KVO. But I don't understand how to do this from an implementation point of view since I cannot find any such notification.

Any help in this regard would be highly appreciated. Thanks.

Please note that this is a framework project. So the framework is built and then added/embedded into another app. I don't have any information about the view controllers in that app. The only thing I can access is UIWindow's root view controller. So, I need to know when a change occurs in it.

回答1:

Got it working. The answer was method swizzling. Not recommended as a first solution to the problem. But if used carefully and you know exactly what you are doing that it is the way to go.

Found a very useful article here: Method Swizzling



回答2:

You can override UIViewController's viewWillAppear and viewWillDisappear to know when a view controller is about to be presented/dismissed.

Alternatively you can use viewDidAppear and viewDidDisappear.

If you want to do the logging on users behalf then you really have two options:

1. provide a base UIViewController sub-class for them to override, which implements a required logic in viewWillAppear/viewWillDisappear methods.

2. implement convenience methods (like logAppearEvent, logDisappearEvent) for them to call manually on their own in their UIViewController subclasses.