简体   繁体   中英

iOS - Monitoring app flow from AppDelegate

I am trying to create Singleton that it would be initialised from AppDelegate . The purpose is to monitor all the UIViewControllers (the active one) and print on console the kind of class (as proof of concept). So my basic idea is to initialise the singleton in AppDelegate and pass as parameter a reference of AppDelegate . Then somehow I must monitor which one is the active view.

For example: View ABCA is the first view in Navigation Controller. My Singleton knows that the current view is A. Then we push view B and Singleton is notified that view B is now the current view. Same with C. Now we pop C and Singleton knows that the current view is B.

Is any kind KVO or NSNotification for notifying my singleton that a new UIView is appeard/removed? Any alternatives for this problem?

After registering for all notification I found out about UINavigationControllerDidShowViewControllerNotification .

With this observer: [notifyCenter addObserver:self selector:@selector(viewAppeared:) name:@"UINavigationControllerDidShowViewControllerNotification" object:nil]; I am able to monitor the activity of the UINavigationController.

You can get current View controller by just making a view controller object in appdelegate like

@property (strong, nonatomic) UIViewController *currentViewController;

and then on the view will Appear of your current view controller give the current reference to the app delegate object like

AppDelegate *myAppd = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    myAppd.currentViewController = self;

This way you get your current active view.

One approach is to pick a particular method you want to know about and intercept it.

Here, I create a category on UIViewController and provide a method I want called whenever the controller's viewWillAppear: would normally be called:

#include <objc/runtime.h>

@implementation UIViewController (Swap)

+ (void)load
{
    NSLog(@"Exchange implementations");
    method_exchangeImplementations(
     class_getInstanceMethod(self, @selector(viewWillAppear:)),
     class_getInstanceMethod(self, @selector(customViewWillAppear:)));
}

- (void)customViewWillAppear:(BOOL)animated
{
    // Call the original method, using its new name
    [self customViewWillAppear:animated];

    NSLog(@"Firing %@ for %@", VIEW_CONTROLLER_APPEARED, self);
    [[NSNotificationCenter defaultCenter] postNotificationName:VIEW_CONTROLLER_APPEARED
                                                        object:self];
}

@end

After that, it's just a case of listening for the notification in whatever object needs to know (eg your Singleton ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM